JavaScript Functions¶
function add(a, b = 0) {
let x = 1;
return a + b;
}
let sum = add(1, 2); // sum = 3
a
andb
are parametersb = 0
defines a default parameterlet x
is a local variable and is not accessible outside the function
Info
- Function declaration is hoisted to the top of the scope.
- Accessing
add
without()
returns the function object and not the resultlet sum = add let result = sum(1, 2) // result = 3
Default Parameters¶
function add(a = 0, b = 0) {
return a + b;
}
Rest Parameters¶
function add(...numbers) {
let sum = 0;
for (let number of numbers) {
sum += number;
}
return sum;
}
this
in Functions¶
const person = {
name: "John",
age: 30,
greet: function () {
console.log(`Hello, my name is ${this.name}`);
},
};
person.greet(); // Hello, my name is John
this
refers to the object that called the functionbind
,call
andapply
can be used to change thethis
value
Arrow Function¶
let add = (a, b) => a + b;
let sum = add(1, 2); // sum = 3
JS Default Functions¶
alert()
- displays an alert box with a message and an OK buttonconsole.log()
- writes a message to the consoleeval()
- evaluates a string as a JavaScript expressionisFinite()
- determines whether a number is finiteisNaN()
- determines whether a value is NaNparseFloat()
- parses a string and returns a floating point numberencodeURI()
- encodes a URIdecodeURI()
- decodes a URIsetTimeout()
- calls a function after a specified number of millisecondssetInterval()
- calls a function repeatedly, after a specified number of milliseconds