1.7 KiB
1.7 KiB
Chapter 4: JavaScript Functions
Function Basics
Simple JS function definition and invocation:
// Function Definition
let greetUser = function () {
console.log('Welcome user!');
}
// Function Invocation
greetUser(); // => 'Welcome user!'
Simple JS function with 1 argument and return:
let square = function (input) {
return input*input;
}
console.log(square(3)); // => 9
Undefined and Null
undefined
:- Senario 1 (Undefined for variable): when variable is declared but without assigning value. JS assign
undefined
to it. - Senario 2 (Undefined for function arguments): Function argument is undefined when no value is parsed. Program hence does not crash.
- Senario 3 (Undefined as function return default value): When function code does not return anything and when it's invoked. It return
undefined
.
- Senario 1 (Undefined for variable): when variable is declared but without assigning value. JS assign
null
:- Emptiness assigned to a varaible: When a value is not sure and want to specify the variable is empty, developer can assign
null
.
- Emptiness assigned to a varaible: When a value is not sure and want to specify the variable is empty, developer can assign
Multiple Arguments and Argument Defaults
Defining functions with multi-arguments:
let func_name = function (arg1, arg2) {
// function body
}
Invoke this function:
func_name(param1, param2);
Dafualt value of arguments can be set in function def:
// Default arguments
let getScoreText = function (name = 'Anonymous', score = 0) {
console.log(name)
console.log(score)
}
getScoreText() // 'Anonymous', 0
Function Scope
Local variable within function only exist in function scope
Template Strings
Template String (aka Template literals): string literal careted using backticket
`This is ${expression}`