You are on page 1of 24

Lecture # 2

Basic JavaScript
Number methods, operators, if else, ternary, truthy
falsy values, functions, Array, Array Methods

Presented by:
Ahsan Ali Mansoor
4+ Years of experience / Team Lead (React JS)
Sr. Full Stack JavaScript Developer at eBridge.tech
Numbers to String Conversion
toFixed()
• toFixed() is used to
• Round off the decimal part.
• format a decimal with specific number of digits to the right of the decimal.
• Parameters: This function accepts a single parameter value . It signifies the
number of digits to appear after the decimal point.
• Return Value: It returns a number in the string representation. The number
has the exact number of digits after the decimal place as mentioned in the
toFixed() function.
• Syntax: number.toFixed( value )
toFixed()
var num = 5.56789;
num.toFixed(); //"6" Round of the value
num.toFixed(10); // "5.5678900000" add aditional zeros’
toString(radix)
• toString() method converts a number to a string.
• Has one optional parameters(radix) you can pass.
• Radix is which base to use for representing a numeric value. Must be an
integer between 2 and 36.
• 2 - The number will show as a binary value
• 8 - The number will show as an octal value
• 16 - The number will show as an hexadecimal value
toString(radix)
var num = 15;
var a = num.toString();
var b = num.toString(2);
var c = num.toString(8);
var d = num.toString(16);
Strings to Number Conversion
parseInt()
• parseInt() has 2 parameters you can pass. First one is string you will parse
and second one is radix.
• In default, the radix parameter will have decimal basis (10).
• If the string starts by "0x" (zero followed by x), the radix is 16 (hexadecimal)
• If the string starts by "0" (zero), the radix is 8 (octal). But this feature is
deprecated.
• If the string starts by any other value, the radix is 10 (decimal)
• Only first number in string will returned.
• Leading and trailing spaces are allowed.
• If there is no match with the rule, parseInt() will returns NaN (means Not a
Number)
parseInt()
parseInt("5") = 5
parseInt("15.00") = 15
parseInt("8.51") = 8
parseInt("23 98 11") = 23
parseInt(" 72 ") = 72
parseInt("-39") = -39
parseInt("21 days") = 21
parseInt("I have 3 dogs") = NaN
parseInt("6", 10) = 6
parseInt("070") = 70
parseInt("16", 8) = 14
parseInt("9", 8) = NaN
parseInt("0x14") = 20
parseInt("3A", 16) = 58
parseFloat()
• parseFloat() only need 1 parameter to pass, the string you want to convert.
Even though this function need string as parameter, you also need to follow
the rule below
• Can only contain plus or minus sign (+ or -), Numeric char (0–9), Dot or
comma sign (. or ,), and space.
• Only first number in string will returned.
• If there is no match with the rule, parseFloat() will returns NaN (means Not a
Number)
parseFloat()
parseFloat("5") // 5
parseFloat("15.00") // 15
parseFloat("8.51") // 8.51
parseFloat("23 98 11") // 23
parseFloat(" 72 ") // 72
parseFloat("-39") // -39
parseFloat("21 days") // 21
parseFloat("I have 3 dogs") // NaN
JavaScript Operators
• Assignment operator
(=)
• JavaScript Arithmetic Operators
(+,-, *, **, /, %, ++, --)
• JavaScript Comparison Operators
(==, ===, !=, !==, >, <, )
• JavaScript Logical Operators
(&&, II, !)
• JavaScript Type Operators
( typeof )
If else Statements
• If else statements gives decision power to the system.
Try with comparison operator and Boolean operator.

Syntax:
If(condition){ code execute when condition true}
else{ code execute when condition false}
Ternary and Switch statement

Switch Statement:
If you use return keyword in cases, you don’t need to use break for
each case. Return keyword break at match case automatically.

The Ternary Operator


• If age greater than 4 go to School and if age greater than 14 go to
college.
• Try with if else and ternary.
Truthy and Falsy Values and Equality Operators
• Falsy values: the values which are considered as false if we use in if
condition

• Falsy values are 5: undefined, null, empty string “”, NaN not a
number, 0

• Truthy values: NOT Falsy values are truthy values


Functions

Functions: for implement DRY (Don’t repeat yourself) Rule. A reusable


piece of code.

Syntax: function functionname(){ code block to be executed}


Call a function: funtionname()

Pass arguments to the functions


function functionname(arg1, arg2){ code block to be executed}
Call function with arguments: functionname(arg1, arg2)
Function Declaration

• Function Declaration / Function Statement: To create a function we can use a function


declaration.
Function Expressions
• Function Expression: Where we store function without name into a variable and call that
function with that variable name where needed.
var whatYouDo = function(age, name, profession){}
Call it as whatYouDo(age, name, profession)

What are JavaScript Expressions: Every piece of code which returns a result is a JavaScript
expression i.e. 2+3 will return 5, whatYouDo(age, name, profession) will return a result so its
a JavaScript Expression too.
Whenever JavaScript expect a value we need to write an expression.
Pure Functions

Pure Functions: Pure functions are functions that accept an input and returns a value
without modifying its argument and any data outside its scope. Its output or return value
must depend on the input/arguments and pure functions must return a value.

function add(a, b) {
let c = a + b;
return c;
}
Function – Return a value
function add(a, b) {
let c = a + b;
return c;
}
var result = add(3,5);
console.log(result);

By default, a function with no return statement returns undefined


value.
Timers / Timer functions
• Timers are used to execute a piece of code at a set time or also to
repeat the code in a given interval of time. This is done by using the
functions setTimeout, setInterval and clearInterval.

• The setTimeout(function, delay) function is used to start a timer that


calls a particular function after the mentioned delay.
• The setInterval(function, delay) function is used to repeatedly
execute the given function in the mentioned delay and only halts
when cancelled. The clearInterval(id) function instructs the timer to
stop.

Timers are operated within a single thread, and thus events might
queue up, waiting to be executed.
Loops / Iterations – for & while
Loop Syntax Example

for (begin; condition; step) { for (let i = 0; i < 3; i++) {


// ... loop body ... // shows 0, then 1, then 2
} alert(i);
}

while (condition) { let i = 0;


// code while (i < 3) {
// so-called "loop body" // shows 0, then 1, then 2
} alert( i );
i++;
}

continue: skip current iteration and continue the rest loop


break: skip current iteration and exit from current loop
Coding Challenge 1
Mark and John are trying to compare their BMI (Body Mass Index),
which is calculated using the formula: BMI = mass / (height * height).
(mass in kg and height in meter).
Steps:
1. Store Mark's and John's mass and height in variables
2. Calculate both their BMIs
3. Create a Boolean variable containing information about whether
Mark has a higher BMI than John.
4. Print a string to the console containing the variable from step 3.
(Something like "Is Mark's BMI higher than John's? true").
Coding Challenge II
Use of: Arithmetic operators, if else, Concatenation, &&
John and Mike both play basketball in different teams. In the latest 3 games, john’s team scored 89,
170 and 103 points, while Mike’s team scored 116, 94 and 123 points.

1. Calculate the average score for each team & log to console.
2. Decide which teams wins in average (highest average score), and print the winner to the
console. Also include the average score in the output.
3. Then change scores to show different winners.
Don’t forget to take into account there might be a draw (the same average score)

EXTRA: Mary also plays basketball, and her team scored 97, 134 and 185 points. Like before, log the
average winner to the console. HINT: you will need the && operator to take the decision.
Like before, change the scores to generate different winners, keeping in mind there might be draws.

average formula = total score of all matches / divided by number of matches


i.e. (match1 score + match2 score + match3score) / 3

You might also like