javascript-basics

Javascript Fundamentals

Keypoints:

  1. JavaScript was initially created to “make web pages alive”.
  2. The programs in this language are called scripts. They can be written right in a web page’s HTML and run automatically as the page loads.
  3. Scripts are provided and executed as plain text. They don’t need special preparation or compilation to run.

Hello World

  1. To run script in browser, add script tag in html file. You can place tag almost anywhere in HTML document.
  2. The <script> tag contains JavaScript code which is automatically executed when the browser processes the tag.
  3. Script files are attached to HTML with the src attribute.
Code Output
```html

Before the script...

...After the script.

```
```console Before the script... // Alert will appear ...After the script. ```
`src="path/"` ```html ```

Code statements, semicolon, comments

Statements

Statements are syntax constructs and commands that perform actions.

Semicolon

  1. A semicolon may be omitted in most cases when a line break exists.
alert("Hello")
alert("World");

// or

alert("Hello");
alert("World");

// Both are correct.

Comments

// This comment occupies a line of its own
alert("Hello");

alert("World"); // This comment follows the statement

/* An example of.
	 a multiline comment.
*/

Modern Mode

  1. "use strict" or 'use strict' is located at the top of a script, the whole script works the “modern” way.
  2. To fully enable all features of modern JavaScript, we should start scripts with “use strict”.
1. 'use strict'
2.
3. funtion (){
4.   ...
5. }

Variables

  1. A variable is a “named storage” for data. We can use variables to store any data.
  2. To create a variable in JavaScript, use the let keyword.
  3. The statement below creates (in other words: declares) a variable with the name “message”:
  4. var instead of let, you may find in old scripts.GOTO
let message; // Declaration
message = "Hello"; // Assigning
alert(message);

let wish = "Hello",
	age = 25,
	name = "Salman"; // Multiline Declaration, separated with comma

message = "World!"; // value changed, old value is removed from the variable
alert(message);

// repeated 'let' leads to an error
let message = "That"; // SyntaxError: 'message' has already been declared

Variable Naming

Keypoints:

  1. Javascript is case-sensitive.
  2. Two limitations on variable naming convention.
    1. The name must contain only letters, digits, or the symbols $ and _.
    2. The first character must not be a digit.
  3. Non-Latin letters are allowed, but not recommended.
  4. Reserved words CANNOT be used as variable names.
  5. Use human-readable names like userName or shoppingCart.
  6. Stay away from abbreviations or short names like a, b, c, unless you really know what you’re doing.
  7. Make names maximally descriptive and concise.
  8. Agree on terms within your team and in your own mind. If a site visitor is called a “user” then we should name related variables currentUser or newUser instead of currentVisitor or newManInTown.
let USERNAME;  // VALID
let userName;  // VALID
let test123;   // VALID

let 1a;        // NOT VALID

let my-name;   // NOT VALID hyphens '-' aren't allowed in the name

let let;       // NOT VALID
let class;     // NOT VALID

Reserved words

These keywords cannot be used as identifiers for variables, functions, classes, etc. anywhere in JavaScript source.

breakcasecatchclass
constcontinuedebuggerdefault
deletedoelseexport
extendsfalsefinalfinally
forfunctionifimplements
importininstanceofnew
nullreturnsuperswitch
thisthrowtruetry
typeofvarvoidwhile
with

b1 c5 d4 e3 f5 i5 n2 r1 s2 t5 v2 w2

The following are only reserved when they are found in strict mode code:

  1. let (also reserved in const, let, and class declarations)
  2. static
  3. yield (also reserved in generator function bodies)

Only reserved in module code or async function bodies:

  1. await

Future reserved words

  1. They have no special functionality at present, but they might at some future time, so they cannot be used as identifiers.
enumimplementsinterfacepackage
privateprotectedpublic

The following are reserved as future keywords by older ECMAScript specifications (ECMAScript 1 till 3).

abstractbooleanbytechar
doublefinalfloatvolatile
gotointlongnative
shortsynchronizedthrowstransient

Identifiers with special meanings

A few identifiers have a special meaning in some contexts without being reserved words of any kind. They include:

  1. arguments (not a keyword, but cannot be declared as identifier in strict mode)
  2. as (import * as ns from “mod”)
  3. async
  4. eval (not a keyword, but cannot be declared as identifier in strict mode)
  5. from (import x from “mod”)
  6. get
  7. of
  8. set

Constants

const variable CANNOT be changed

const myBirthday = "18.04.1982";
myBirthday = "01.01.2001"; // error, can't reassign the constant!

Data types

There are eight basic data types in JavaScript.

NumberBigIntStringBoolean
NullUndefinedObjectsSymbols

Number

  1. The number type represents both integer and floating point numbers.
  2. Also special numeric values which also belong to this data type: Infinity, -Infinity and NaN.
  3. The script will never stop with a fatal error (“die”). At worst, we’ll get NaN as the result.
  4. Infinity represents the mathematical Infinity ∞. It is a special value that’s greater than any number.
  5. NaN represents a computational error. It is a result of an incorrect or an undefined mathematical operation, for instance.
  6. Integer values larger than (253-1) (that’s 9007199254740991), or less than -(253-1) for negatives.
  7. Please go through this link for more details on Numbers ```javascript let num = 123; num = 12.345;

alert(1 / 0); // Infinity

alert(Infinity); // Infinity

alert(“not a number” / 2); // NaN, such division is erroneous

alert(NaN + 1); // NaN alert(3 * NaN); // NaN alert(“not a number” / 2 - 1); // NaN

console.log(9007199254740991 + 1); // 9007199254740992 console.log(9007199254740991 + 2); // 9007199254740992


```js
if(NaN) console.log(true)
else console.log(false)
// false

if(undefined) console.log(true)
else console.log(false)
// false

if(null) console.log(true)
else console.log(false)
// false

if(0) console.log(true)
else console.log(false)
// false

if("") console.log(true)
else console.log(false)
// false

BigInt

  1. Bigint can store greater than number type upto 1.7976931348623157 * 10308.
  2. Used in cryptography or microsecond-precision timestamps.
  3. A BigInt value is created by appending n to the end of an integer.
// the "n" at the end means it's a BigInt
const bigInt = 1234567890123456789012345678901234567890n;

String

  1. A string in JavaScript must be surrounded by quotes.
  2. Please go through this link for more details on Strings
let str = "Hello"; //Double quotes
let str2 = "Single quotes are ok too"; //Single quotes
let phrase = `can embed another ${str}`; //Backticks

alert(`the result is ${1 + 2}`); // the result is 3, embed an expression using backticks

Boolean

  1. The boolean type has only two values: true and false.
let nameFieldChecked = true; // yes, name field is checked
let ageFieldChecked = false; // no, age field is not checked

let isGreater = 4 > 1;
alert(isGreater); // true (the comparison result is "yes")

Null

  1. The special null value does not belong to any of the types described above.
  2. null is not a reference to a non-existing object or a null pointer like in some other languages.
  3. It’s just a special value which represents nothing, empty or value unknown.
let age = null;

console.log(typeof age); // object

Undefined

  1. The special value undefined also stands apart. It makes a type of its own, just like null.
  2. The meaning of undefined is “value is not assigned”.
  3. If a variable is declared, but not assigned, then its value is undefined:
let age;
alert(age); // shows "undefined"

let age = 100;
// change the value to undefined
age = undefined; // explicitly assign undefined to a variable
alert(age); // "undefined"

Objects

  1. It is used to store and collections of data and more complex entities.
  2. It’s Non-primitive Data type

Please go through this link for more on Objects

Symbols

  1. It is used to create unique identifier for objects

Please go through this link for more details on Symbols

typeof Operator

  1. The typeof operator returns the type of the operand.
  2. It’s useful when we want to do a quick check.
typeof undefined // "undefined"

typeof 0 // "number"

typeof 10n // "bigint"

typeof true // "boolean"

typeof "foo" // "string"

typeof Symbol("id") // "symbol"

typeof Math // "object"  (1)

typeof null // "object"  (2) It'a an error, null is not an object. See null section

typeof alert // "function"  (3)

Interaction(alert, prompt, confirm…..)

To interact with user, we have alert, prompt and confirm functions in javascript.

1 Alert

  1. It shows a message and waits for the user to press OK.
  2. All parameters are convert to string type.
alert("Hello");

2 Prompt

  1. It shows a modal window with a text message, an input field for the visitor, and the buttons OK/Cancel.
result = prompt(title, [default]);

// title =  text to show the visitor.
// default = the initial value for the input field [optional].

let age = prompt('How old are you?', 100);
alert(`You are ${age} years old!`); // You are 100 years old!

NOTE: [...] Square Brackets means Optional parameter

3 Confirm

  1. Shows a modal window with a question and two buttons: OK and Cancel.
  2. The result is true if OK is pressed and false otherwise.
result = confirm(question);

let isBoss = confirm("Are you the boss?");
alert( isBoss ); // true if OK is pressed

Type Conversions

  1. It’s an Explicitly process conversion, convert a value to the expected data type,
  2. Type conversion is useful when we want String value instead of boolean value.

String

  1. Convert a any value to string type.
let value = true;
alert(typeof value); // boolean

value = String(value); // now value is a string "true"
alert(typeof value); // string

Number

  1. Conver a value to number type.
  2. Value must be valid number, otherwise it convert to NaN type.
let str = "123";
alert(typeof str); // string

let num = Number(str); // becomes a number 123

alert(typeof num); // number

let age = Number("an arbitrary string instead of a number");

alert(age); // NaN, conversion failed
Value Becomes
`undefined` `NaN`
`null` `0`
`true and false` `1` and `0`
`string` Whitespaces (includes spaces, tabs `\t`, newlines `\n` etc.) from the start and end are removed. If the remaining string is empty, the result is `0`. Otherwise, the number is “read” from the string. An error gives `NaN`.
alert( Number("   123   ") ); // 123
alert( Number("123z") );      // NaN (error reading a number at "z")
alert( Number(true) );        // 1
alert( Number(false) );       // 0

Boolean

  1. Values that are intuitively empty like 0, an empty string, null, undefined, and NaN, become false.
  2. Other values become true.
alert( Boolean(1)   );  // true
alert( Boolean(0)   );  // false
alert( Boolean("0") );  // true Zero is a string, not a number 

alert( Boolean("hello") ); // true
alert( Boolean("") ); // false

Basic operators, maths

  1. Addition +
  2. Subtraction -
  3. Multiplication *
  4. Division /
  5. Remainder % (NOT related to percent)
  6. Exponentiation **
alert( 5 + 2 ); // 7, 
alert( 8 - 3 ); // 5, 
alert( 8 * 2 ); // 16, 
alert( 5 / 2 ); // 2, the quotient of 5 divided by 2
alert( 8 % 2 ); // 0, the remainder of 8 divided by 2
alert( 2 ** 4 ); // 16, 2 to the power of 4.

alert( 4 ** (1/2) ); // 2 (power of 1/2 is the same as a square root)
alert( 8 ** (1/3) ); // 2 (power of 1/3 is the same as a cubic root)

String concatenation

  1. If the binary + is applied to strings, it merges (concatenates) them.
  2. The binary + is the only operator that supports strings in such a way. Other arithmetic operators work only with numbers and always convert their operands to numbers.
  3. The unary plus or, in other words, the plus operator + applied to a single value, doesn’t do anything to numbers. But if the operand is not a number, the unary plus converts it into a number.
let s = "my" + "string";
alert(s); // mystring

// ---->>  BINARY <<-----

alert( '1' + 2 ); // "12"
alert( 2 + '1' ); // "21"

alert( 6 - '2' ); // 4, converts '2' to a number
alert( '6' / '2' ); // 3, converts both operands to numbers

// ---->> UNARY <<-----

// No effect on numbers
let x = 1;
alert( +x ); // 1

let y = -2;
alert( +y ); // -2

// Converts non-numbers to numbers
alert( +true ); // 1
alert( +"" );   // 0

let apples = "2";
let oranges = "3";

// both values converted to numbers before the binary plus
alert( +apples + +oranges ); // 5

// the longer variant
// alert( Number(apples) + Number(oranges) ); // 5

Operator precedence

  1. As we can see, the “unary plus” has a priority of 14 which is higher than the 11 of “addition” (binary plus). That’s why, in the expression "+apples + +oranges", unary pluses work before the addition.
  2. Higher values give the High Priority
    1. 14 is High priority
    2. 4 is low priority than 14
PreccedencenameSign
14 unary plus `+`
14 unary negation `-`
13 exponentiation `**`
12 multiplication `*`
12 division `/`
11 addition `+`
11 subtraction `-`
... ... `...`
2 assignment `=`
... ... `...`

Modify-in-place

  1. An operator to a variable and store the new result in that same variable.
  2. Short “modify-and-assign” operators exist for all arithmetical and bitwise operators: /=, -=, etc.
let n = 2;
n += 5; // now n = 7 (same as n = n + 5)
n *= 2; // now n = 14 (same as n = n * 2)

alert( n ); // 14
// -------------------
n = 2;
n *= 3 + 5; // right part evaluated first, same as n *= 8
alert( n ); // 16

Increment & decrement

  1. Increment ++ increases a variable by 1. It is in postfix form.
  2. Decrement -- decreases a variable by 1. It is in prefix form.
  3. Increment/decrement can only be applied to variables. Trying to use it on a value like 5++ will give an error.
  4. These precedence is higher than most other arithmetical operations.
let counter = 2;
counter++;        // works the same as counter = counter + 1, but is shorter
alert( counter ); // 3

counter = 2;
counter--;        // works the same as counter = counter - 1, but is shorter
alert( counter ); // 1

Bitwise operators

  1. These operators are used very rarely, when we need to fiddle with numbers on the very lowest (bitwise) level.

  2. AND ( & )
  3. OR ( | )
  4. XOR ( ^ )
  5. NOT ( ~ )
  6. LEFT SHIFT ( << )
  7. RIGHT SHIFT ( >> )
  8. ZERO-FILL RIGHT SHIFT ( >>> )

You can read the Bitwise Operators in this MDN docs.

Comma

  1. The comma operator , is one of the rarest and most unusual operators. Sometimes, it’s used to write shorter code.
  2. It has very low Precedence.
let a = (1 + 2, 3 + 4);

alert( a ); // 7 (the result of 3 + 4)

//the first expression 1 + 2 is evaluated and its result is thrown away. Then, 3 + 4 is evaluated and returned as the result.

Comparisions

  1. Greater/Less than a > b a < b
  2. Greater/less than or equals a >= b, a <= b
  3. Equals a == b
  4. Not equals a != b

All comparisions operators return a boolean value.

alert( 2 > 1 );  // true (correct)
alert( 2 == 1 ); // false (wrong)
alert( 2 != 1 ); // true (correct)
let result = 5 > 4; // assign the result of the comparison
alert( result ); // true

String comparisions

  1. Comparison operators return a boolean value.
  2. Strings are compared letter-by-letter in the “dictionary” order.
  3. When values of different types are compared, they get converted to numbers (with the exclusion of a strict equality check).
  4. The values null and undefined equal == each other and do not equal any other value.
  5. Be careful when using comparisons like > or < with variables that can occasionally be null/undefined.
  6. Checking for null/undefined separately is a good idea.
alert( 'Z' > 'A' ); // true
alert( 'Glow' > 'Glee' ); // true
alert( 'Bee' > 'Be' ); // true

The algorithm to compare two strings is simple:

  1. Compare the first character of both strings.
  2. If the first character from the first string is greater (or less) than the other string’s, then the first string is greater (or less) than the second. We’re done.
  3. Otherwise, if both strings’ first characters are the same, compare the second characters the same way.
  4. Repeat until the end of either string.
  5. If both strings end at the same length, then they are equal. Otherwise, the longer string is greater.

In the first example above, the comparison 'Z' > 'A' gets to a result at the first step.

The second comparison 'Glow' and 'Glee' needs more steps as strings are compared character-by-character:

G is the same as G. l is the same as l. o is greater than e. Stop here. The first string is greater.

alert( '2' > 1 ); // true, string '2' becomes a number 2
alert( '01' == 1 ); // true, string '01' becomes a number 1

// for boolean values, true becomes 1 and false becomes 0.
alert( true == 1 ); // true
alert( false == 0 ); // true

let a = 0;
alert( Boolean(a) ); // false

let b = "0";
alert( Boolean(b) ); // true

alert(a == b); // true!

Strict equality

  1. A strict equality operator === checks the equality without type conversion.
alert( 0 === false ); // false

alert( null === undefined ); // false ---> strict equality
alert( null == undefined ); // true   ---> strict equality

// null vs 0

alert( null > 0 );  // (1) false
alert( null == 0 ); // (2) false
alert( null >= 0 ); // (3) true

alert( undefined > 0 ); // false (1)
alert( undefined < 0 ); // false (2)
alert( undefined == 0 ); // false (3)

Conditions

  1. if statement evaluates a condition in parentheses and, if the result is true, executes a block of code.
  2. You can use ? statement instead of if statements.
  3. A number 0, an empty string “”, null, undefined, and NaN all become false. Because of that they are called “falsy” values. Remaining are true.
  4. if statement fails then else block is execute. if statement may contain optional else block.
  5. else if statement test several variants of a condition.
  6. conditional operator ? looks like this let result = condition ? value1 : value2;
let year = prompt('In which year was ECMAScript-2015 specification published?', '');

if (year == 2015) alert( 'You are right!' );

// if and else
if (year == 2015) {
	alert( 'You guessed it right!' );
} else {
	alert( 'How can you be so wrong?' ); // any value except 2015
}

// if and else if

//year = 2015

if (year < 2015) {
	alert( 'Too early...' );
} else if (year > 2015) {
	alert( 'Too late' );
} else {
	alert( 'Exactly!' ); // this one may execute
}

// conditional operator ?
let accessAllowed;
let age = prompt('How old are you?', '');

if (age > 18) {
	accessAllowed = true;
} else {
	accessAllowed = false;
}

alert(accessAllowed);

// can be written in ? operator

let accessAllowed = (age > 18) ? true : false;

Logical operators

  1. There are four logical operators in JavaScript: || (OR), && (AND), ! (NOT), ?? (Nullish Coalescing).
  2. || OR operator => If any of its arguments are true, it returns true, otherwise it returns false.
  3. || operator evaluates operands from left to right. For each operand, converts it to boolean. If the result is true, stops and returns the original value of that operand.
  4. && AND operator returns true if both operands are truthy and false otherwise.
  5. For each operand, converts it to a boolean. If the result is false, stops and returns the original value of that operand.
  6. Precedence of AND && is higher than OR ||.
  7. ! (NOT) operator returns reverse value.
  8. !! Double NOT is sometimes used for converting a value to boolean type. Similar to Boolean("non-empty string")
  9. The precedence of NOT ! is the highest of all logical operators, so it always executes first, before && or ||.
//   ||
alert( true || true );   // true
alert( false || true );  // true
alert( true || false );  // true
alert( false || false ); // false

//   &&
alert( true && true );   // true
alert( false && true );  // false
alert( true && false );  // false
alert( false && false ); // false

//   !
alert( !true ); // false
alert( !0 ); // true

Nullish coalescing operator ‘??’

  1. A value is defined when it’s neither null nor undefined.
  2. The result of a ?? b is: - if a is defined, then a, - if a isn’t defined, then b.
  3. The precedence of the ?? operator is the same as ||. only a bit higher than ? and =.
  4. It’s forbidden to use it with || or && without explicit parentheses.
// set height=100, if height is null or undefined
height = height ?? 100;

Loops: while & for

  1. A single execution of the loop body is called an iteration.

While Loop

  1. Loop iterate the body until the condition becomes false.
  2. Curly braces are not required for a single-line body.
while (condition) {
	// code
	// so-called "loop body"
}

let i = 0;
while (i < 3) { // shows 0, then 1, then 2
	alert( i );
	i++;
}

do…while loop

  1. The loop will first execute the body, then check the condition.
  2. Use when you need to run the code atleast once even though the condition is wrong.
do {
	// loop body
} while (condition);

let i = 0;
do {
	alert( i );
	i++;
} while (i < 3);

for loop

for (begin; condition; step) {
	// ... loop body ...
}

for (let i = 0; i < 3; i++) { // shows 0, then 1, then 2
	alert(i);
}

Break and Continue

  1. Normally, a loop exits when its condition becomes falsy.
let sum = 0;

while (true) {

	let value = +prompt("Enter a number", '');

	if (!value) break; // (*)

	sum += value;

}
alert( 'Sum: ' + sum );

Continue

  1. It stops the current iteration and forces the loop to start a new one (if the condition allows).
  2. If you don’t want to do anything in the current iteration, and would like to go forward to next one, use continue.
for (let i = 0; i < 10; i++) {

	// if true, skip the remaining part of the body
	if (i % 2 == 0) continue;

	alert(i); // 1, then 3, 5, 7, 9
}

Label

  1. A label is an identifier with a colon before a loop.
  2. Labels do not allow to jump anywhere.
  3. A break directive must be inside a code block.
  4. A label is the only way for break/continue to escape a nested loop to go to an outer one.
outer: for (let i = 0; i < 3; i++) {

	for (let j = 0; j < 3; j++) {

		let input = prompt(`Value at coords (${i},${j})`, '');

		// if an empty string or canceled, then break out of both loops
		if (!input) break outer; // (*)

		// do something with the value...
	}
}

alert('Done!');

Switch statements

  1. The switch has one or more case blocks and an optional default.
  2. It is similar to if else if statements.
  3. The value of x is checked for a strict equality.
switch(x) {
	case 'value1':  // if (x === 'value1')
		...
		[break]

	case 'value2':  // if (x === 'value2')
		...
		[break]

	default:
		...
		[break]
}

Functions

  1. function is some block of code, to be called many times without repetition.
  2. To create a function we can use a function declaration.
  3. function is should be declared first, before calling it.
  4. When JavaScript prepares to run the script, it first looks for global Function Declarations in it and creates the functions. We can think of it as an initialization stage.
  5. A Function Declaration can be called earlier than it is defined.
alert(message);             // prebuilt function
prompt(message, default);   // prebuilt function
confirm(question);          // prebuilt function


function showMessage() {    // custom function
	alert( 'Hello everyone!' );
}

showMessage();
showMessage();

Local variables

  1. A variable declared inside a function is only visible inside that function.
function showMessage() {
	let message = "Hello, I'm JavaScript!"; // local variable

	alert( message );
}

showMessage(); // Hello, I'm JavaScript!

alert( message ); // <-- Error! The variable is local to the function

Outer variables

  1. A variable declared outside a function, also known as Global variable.
  2. function has full access to the outer variable. The outer variable is only used if there’s no local one.
  3. If a same-named variable is declared inside the function then it shadows the outer one. For instance, in the code below the function uses the local userName. The outer one is ignored.
  4. Maximize the use of local variable instead of global variable.
let userName = 'John';

function showMessage() {
	let userName = "Bob"; // declare a local variable

	let message = 'Hello, ' + userName; // Bob
	alert(message);
}

// the function will create and use its own userName
showMessage();

alert( userName ); // John, unchanged, the function did not access the outer variable

Parameters

  1. Pass the arbitrary data to functions using parameters.
  2. When the function is called, the given values are copied to local variables. from and text. You can use outside the function.
  3. It is also called an argument. In simple terms, We declare functions listing their parameters, then call them passing arguments.
function showMessage(from, text) {
	from = '*' + from + '*'; // now it becomes, *Ann*
	alert( from + ': ' + text );
}

let from = "Ann";
showMessage(from, "Hello"); // *Ann*: Hello

// the value of "from" is the same, the function modified a local copy
alert( from ); // Ann

Default values

  1. If a function is called, but an argument is not provided, then the corresponding value becomes undefined.
  2. For more info, follow this link
function showMessage(from, text = "no text given") {
	alert( from + ": " + text );
}

showMessage("Ann"); // Ann: no text given

Returning a value

  1. A function can return a value back into the calling code as the result.
  2. When the execution reaches it, the function stops, and the value is returned to the calling code. (assigned to result above)
  3. A function with an empty return or without it returns undefined
function sum(a, b) {
	return a + b;
}

let result = sum(1, 2);
alert( result ); // 3


// empty return
function doNothing() { /* empty */ }
alert( doNothing() === undefined ); // true

function doNothing() {
	return;
}
alert( doNothing() === undefined ); // true

Naming a function

  1. Functions are actions. So their name is usually a verb. It should be brief, as accurate as possible and describe what the function does.
  2. One function – one action

Function starting with:
get…” – return a value,
calc…” – calculate something,
create…” – create something,
check…” – check something and return a boolean, etc.

showMessage(..)     // shows a message
getAge(..)          // returns the age (gets it somehow)
calcSum(..)         // calculates a sum and returns the result
createForm(..)      // creates a form (and usually returns it)
checkPermission(..) // checks a permission, returns true/false

Function expressions

  1. As the function creation happens in the context of the assignment expression (to the right side of =), this is a Function Expression.
  2. After function declaration, no need to write a name, called anonymous function.
let sayHi = function() { // function expression
	alert( "Hello" );
};

Function is a value

  1. No matter how the function is created, a function is a value.
  2. A function is a special value, in the sense that we can call it like sayHi().
  3. We can copy a function to another variable. copy without parathesis, otherwise it will the function.
  4. The semicolon ; is recommended at the end of the statement, it’s not a part of the function syntax.
function sayHi() {
	alert( "Hello" );
}

alert( sayHi ); // shows the function code

// ------------------------------------
// ------------------------------------

function sayHi() {   // (1) create
	alert( "Hello" );
}

let func = sayHi;    // (2) copy
// let func = sayHi(); // ❌ wrong, remove paranthesis to copy

func(); // Hello     // (3) run the copy (it works)!
sayHi(); // Hello    //     this still works too (why wouldn't it)

let sayHi = function() {
	// ...
};                          // semicolon at end of expression

Callback functions

  1. A callback function is a function that is passed as an argument to another function.
  2. Fore more info, follow this link.
  3. A function is a value representing an action.
function ask(question, yes, no) {
	if (confirm(question)) yes()
	else no();
}

function showOk() {
	alert( "You agreed." );
}

function showCancel() {
	alert( "You canceled the execution." );
}

// usage: functions showOk, showCancel are passed as arguments to ask
ask("Do you agree?", showOk, showCancel);

Function Expression vs Function Declaration

  1. A Function Declaration can be called earlier than it is defined (hoisted).
  2. When JavaScript prepares to run the script, it first looks for global Function Declarations in it and creates the functions. We can think of it as an “initialization stage”, called hoisting
  3. And after all Function Declarations are processed, the code is executed. So it has access to these functions.
```js // Function Declaration function sum(a, b) { return a + b; } ``` ```js // Function Expression let sum = function(a, b) { return a + b; }; ```
sayHi("John"); // Hello, John WORKS 

function sayHi(name) {
	alert( `Hello, ${name}` );
}

// FUNCTION DECLATION CAN WRITE ABOVE OR BELOW CALLER.
```js function sayHi() { // (1) create alert( "Hello" ); } let func = sayHi; // (2) copy func(); // Hello // (3) run the copy (it works)! sayHi(); // Hello // this still works too (why wouldn't it) ``` ```js let sayHi = function() { // (1) create alert( "Hello" ); }; let func = sayHi; // same as beside mention ```
Calling before declaration
```js sayHi("John"); // Hello, John function sayHi(name) { alert( `Hello, ${name}` ); } ``` ```js sayHi("John"); // error! let sayHi = function(name) { // (*) no magic any more alert( `Hello, ${name}` ); }; ```

Arrow functions, the basics

  1. Arrow function is similar to function expression, but only different in syntax.
  2. Arrow function can have Single and multi-line.
  3. Single line automatically returns the expression and Multi-line needs return statement. - Without curly braces: (...args) => expression, function evaluate implicitly returns the result - With curly braces: (...args) => { return body } but we need an explicit return to return something.
  4. More to come, please visit this page
Arrow functionFunction Expression
```js let func = (arg1, arg2, ..., argN) => expression; ``` ```js let func = function(arg1, arg2, ..., argN) { return expression; }; ```
let sum = (a, b) => a + b; // single line function

alert( sum(1, 2) ); // 3


// --------------------
// --------------------

let sum = (a, b) => {  // the curly brace opens a multiline function
	let result = a + b;
	return result; // if we use curly braces, then we need an explicit "return"
};

alert( sum(1, 2) ); // 3
let double = n => n * 2;
// roughly the same as: let double = function(n) { return n * 2 }

alert( double(3) ); // 6

Resources

  1. Javascript
  2. MDN Keywords.