U02 1JavasriptFundamentalsv8
U02 1JavasriptFundamentalsv8
Index
● Variables and Data Types ● Arrays
● Operators ● For loops
● Rules for Type Coercion ● Arrays…
● Let and Scope ● Default parameters
● Problem with var ● Rest parameter
● const ● Spread operator
● Strings ● Falsy values
● Template literals ● Nullish coalescing operator
● Conditionals
● Loops
● Functions
Variables and Data Types
2
Primitive data types
● There are a few types of values that JavaScript uses:
Variable Explanation Example
This is a sequence of text known as a string. To signify that the value is a string, let myVariable = 'Bob'; or
String
enclose it in single or double quote marks. let myVariable = "Bob";
Number This is a number. Numbers don't have quotes around them. let myVariable = 10;
This is a True/False value. The words true and false are special keywords that don't
Boolean let myVariable = true;
need quote marks.
2
Primitive data types
● Special primitive types:
○ null for unknown values – a standalone type that has a single value
null.
○ undefined for unassigned values – a standalone type that has a single
value undefined.
2
Variables
● Primitive types: undefined, number, string, boolean, function, object
2
Variables
● Weak, dynamic typing
● Variables have the type of the last thing assigned to it
let somevar;
let somevar;
typeof somevar; // undefined
typeof somevar; // undefined
somevar = 25;
let somevar = () => {};
typeof somevar // number
typeof somevar; // function
somevar = “hello”;
typeof somevar; // string
2
Operators
Operator Explanation Symbol(s) Example
Add two numbers together or combine 6 + 9;
Addition +
two strings. 'Hello ' + 'world!';
9 - 3;
These do what you'd expect them to do
Subtraction, Multiplication, Division -, *, / 8 * 2; // multiply in JS is an asterisk
in basic math.
9 / 3;
As you've seen already: this assigns a
Assignment = let myVariable = 'Bob';
value to a variable.
This performs a test to see if two values
let myVariable = 3;
Strict equality are equal and of the same data type. It ===
myVariable === 4;
returns a true/false (Boolean) result.
For "Not", the basic expression is true, but the comparison
returns false because we negate it:
let myVariable = 3;
myVariable !== 3;
2
Operators - Loose vs Strict Equality
2
Operators - Loose vs Strict Equality
const a = 100; const a = 100;
const b = '100'; const b = '100';
● The variable a is converted to a string ● Triple equals checks for the types of
before making the comparison. the operands first – and those types
● It is important to note that the actual differ in this example, a is number and
comparing. 2
Operators - Loose vs Strict Equality
const a = true;
const b = 'true';
2
Operators - Loose vs Strict Inequality
const a = 2; const a = 2;
● The JavaScript not equal or inequality operator (!=) checks whether two
values are not equal and returns a boolean value. This operator tries to
compare values irrespective of whether they are of different types.
● However, the “!==” or Strict inequality operator does not attempt to do so
and returns false if the values are unequal or of different types.
2
Rules for Type Coercion
● If either operand is a string, the other operand will be converted to a string.
● If either operand is a number, the other operand will be converted to a number.
● If either operand is a boolean, it will be converted to a number (true becomes 1
and false becomes 0).
● If one operand is an object and the other is a primitive value, the object will be
converted to a primitive value before the comparison is made.
● If one of the operands is null or undefined, the other must also be null or
undefined to return true. Otherwise it will return false.
2
Let and Scope
2
Let example
let a = 50;
let b = 100;
if (true) { ● The variable a is found both in the
let a = 60;
scope of this script, and in the scope
let c = 10;
console.log(a/c); // 6 of the if statement block
console.log(b/c); // 10 ● The variable a within the block can be
}
console.log(c); // 10
considered a different variable than
console.log(a); // 50 the variable a outside the block
2
Problem with var
var name = "my name";
var myAge = 22;
● var variable can be re-declared and
if(myAge > 18) {
updated
var name = "another person name";
} ● re-declaration allows declaring more
than one variable with the same
console.log(name);
//output => "another person name"
name, because of this reason, if we
declare a new variable by mistake, it
will override the original variable
value.
2
var vs let
var a = 5;
let a = 5;
console.log(a); // 5
{
console.log(a); // 5
var a = 3; {
console.log(a); // 3 let a = 3;
} console.log(a); // 3
console.log(a); // 3 }
console.log(a); // 5
2
var vs let
var a = 2;
let a = 2;
for(var a = 0; a < 3; a++) {
for(let a = 0; a < 3; a++) {
console.log('hello');
console.log('hello');
}
}
console.log(a); // 3
console.log(a); // 2
● When a variable declared with var is ● When a variable declared with let is
used in a loop, the value of that used in a loop, the value of a variable
variable changes does not change
2
const
2
const example
2
Strings
let greeting = "Hello";
let farewell = 'Bye';
let word = 'text';
// Ternary
result = our_value ? 'we got a value' : 'no value' ;
2
While Loops
let answerQuestion = function () {
while (condition) { let answer = prompt("What is 4 + 4" );
if (answer == "8") {
// body of loop return true ;
} else {
}
return false ;
}
}
let answer = false;
while (answer != true) {
answer = answerQuestion();
}
alert("Correct Answer!" );
2
Do-While Loops
// program to display numbers
do { let i = 1;
const n = 5;
// body of loop
// do...while loop from 1 to 5
} while (condition)
do {
console.log(i);
i++;
} while(i <= n);
2
Functions
Our First Function
function helloWorld(first_name, last_name) {
let message = "Hello World " + first_name + " " + last_name;
return message;
}
2
Functions
5 ways to define
1. Function declaration 2. Function expression
function sum(a, b) { let sum = function(a, b) { 5. Function constructor
return a+b; return a+b; let sum = new Function(
} } ‘a’,
sum(2,3); sum(2,3); ‘b’,
‘return a+b’
};
3. Arrow function 4. IIFE function sum(2,3);
let sum =(a, b) => { (function(a, b) {
return a+b; return a+b;
} })(2,3);
sum(2,3);
Arrow Functions
2
Arrow Functions Example
function oldOne(name) {
console.log("Hello " + name);
} ● The parameters are named in the
oldOne("Kay"); parentheses outside the name of the
function
// New Syntax ● Note how you assign a variable to a function
let newOne = (name) => { (and can use let for scope)
console.log("Hello " + name);
}
newOne("Kay");
2
Arrow Functions Example
● Arrow functions are handy for simple actions, especially for one-liners. They come in two
flavors:
○ Without curly braces: (...args) => expression – the right side is an expression: the
function evaluates it and returns the result. Parentheses can be omitted, if there’s
only a single argument, e.g. n => n*2.
○ With curly braces: (...args) => { body } – brackets allow us to write multiple
statements inside the function, but we need an explicit return to return something.
2
for Loops
for (initialExpression; condition; updateExpression) {
// for loop body
}
function countToX(x) {
let message = "";
for(let i = 0; i <= x; i = i+1) {
message = message + i + " ";
}
return message;
}
2
Arrays
2
Arrays
2
Array - Map
Sintax
reduce(callbackFn)
reduce(callbackFn, initialValue)
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce((accumulator, currentValue) =>
accumulator + currentValue, initialValue );
console.log(sumWithInitial );
// Expected output: 10
2
Array - Filter
Sintax
reduce(callbackFn)
reduce(callbackFn, initialValue)
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce((accumulator, currentValue) =>
accumulator + currentValue, initialValue );
console.log(sumWithInitial );
// Expected output: 10
2
Array - Reduce
Sintax
reduce(callbackFn)
reduce(callbackFn, initialValue)
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue );
console.log(sumWithInitial );
// Expected output: 10
2
Array - Map
const array1 = [1, 4, 9, 16];
console.log(map1);
// Expected output: Array [2, 8, 18, 32]
2
Array - Filter
console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]
2
Array - Reduce
Sintax
reduce(callbackFn)
reduce(callbackFn, initialValue)
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, current) => accumulator + current, initialValue);
// 0 + 1 + 2 + 3 + 4
2
Array - foreach
const array1 = ['a', 'b', 'c'];
2
Primitive data types
2
for…of loops
Old Way New Way
let a = [5,6,7];
var a = [5,6,7];
let sum = 0;
var sum = 0;
for (let ent of a) {
for (var i = 0; i < a.length; i++) {
sum += ent;
sum += a[i];
}
} ● Iterate over arrays, strings, Map, Set, without
Iterator over an array using indexes.
2
for...of vs for...in
● For of (iterates over values):
for(let student of students) {
console.log(student);
} //Prints out all student names
2
for … in loops
const student = { // using for...in
name: 'Monica', for (let key in student) {
class: 7, // display the properties
age: 12 console.log(`${key} => ${student[key]}`);
} }
2
for...of Vs for...in
for...of for...in
The for...of loop is used to The for...in loop is used to iterate through
iterate through the values the keys of an object.
of an iterable.
The for...of loop cannot be You can use for...in to iterate over an
used to iterate over an iterable such arrays and strings but you
object. should avoid using for...in for iterables.
2
Array - forEach
Sintax
array.forEach(callback(element [, index] [, arr])[, thisValue])
2
Array - forEach
[2, 5, , 9].forEach(logArrayElements);
// Prints out:
// a[0] = 2
// a[1] = 5
// a[2] = 9
//Note that the 2nd index is avoided since there is no element in that
position in the array.
2
Array
push, .pop, .shift, and .unshift
2
Array
.push, .pop, .shift, and .unshift
Javascript Basics: Use .push, .pop, .shift, and .unshift to Manipulate Arrays
2
Arrays <-> Strings
● In JavaScript, strings are immutable
● JavaScript includes many built-in functions for creating and manipulating strings in
various ways.
● Very often there are situations where strings have to be converted into arrays in order to
manipulate their content.
● There are many ways to split a string into character arrays, i.e.:
2
Destructuring arrays
Old Way New Way
var a = arr[0];
var b = arr[1]; let [a,b,c] = arr;
var c = arr[2];
var a = arr[0];
var b = arr[1]; console.log(a); //1
● You can skip what you don't want by leaving that position blank
Cloning arrays
● Shallow copy
○ Spread Operator
○ Array.from
○ Array.slice
○ Array.map
○ While Loop
○ For Loop
● Deep copy
○ JSON.parse and JSON.stringify
Cloning arrays
const fruits = ["Strawberry", "Mango"];
a = a || 1;
b = b || "Hello"; }
2
Default Parameters
● Default function parameters allow named parameters to be initialized with default
values if no value or undefined is passed.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters
Rest parameter …
Old Way New Way
function myFunc() {
for (var i = 0; i < arguments. length; i++){
console.log(arguments[ i]); function myFunc (a,b,...theArgsArray) {
} theArgsArray. forEach(e=>console.log(e));
} }
myFunc("Nick", "Anderson" , 10, 12, 6); myFunc("Nick", "Anderson" , 10, 12, 6);
// Nick // 10
// Anderson // 12
// 10 // 6
// 12
// 6
Additional parameters can be placed into a
Parameters not listed but passed can be named array.
accessed using the arguments array.
Rest parameter…
2
Rest parameter…
let sumElements = (...arr) => {
console.log(arr); // [10, 20, 40, 60, 90]
● You can pass a variable number of parameters
let sum = arr.reduce((accE,curE)=>accE+curE);
console.log(sum);
● Those parameters are available as an array
}
inside the function
sumElements(10, 20, 40, 60, 90);
sumElements(10, 20, 90);
2
Spread operator …
Old Way New Way
var iniArr = ['My', 'name', 'is']; const iniArr = ['My', 'name', 'is'];
7
Spread operator …
Old Way New Way
let arr1 = [ 1, 2, 3]; let arr1 = [ 1, 2, 3];
let arr2 = arr1; // copy using spread syntax
console.log(arr1); // [1, 2, 3] let arr2 = [...arr1];
console.log(arr2); // [1, 2, 3]
// append an item to the array
// append an item to the array arr1.push(4);
arr1.push(4);
console.log(arr1); // [1, 2, 3, 4]
console.log(arr1); // [1, 2, 3, 4] console.log(arr2); // [1, 2, 3]
console.log(arr2); // [1, 2, 3, 4]
Objects are assigned by reference and not by Arrays can be copied using the Spread
values Operator
Falsy values
if (false) { if (-0) {
// Not reachable // Not reachable They are coerced to false in Boolean contexts
} }
if (null) { if (0n) {
● || returns the first truthy value.
// Not reachable // Not reachable ● ?? returns the first defined value.
} }
if (undefined ) { if (NaN) {
// Not reachable // Not reachable
} }
if (0) { if ("") {
// Not reachable // Not reachable
} }
7
Nullish coalescing operator (??)
let height = 0;
console.log(height || 300); // 300
console.log(height ?? 300); // 0