JAVASCRIPT
JavaScript is primarily known as the language of most modern web
browsers. JavaScript is a powerful, flexible, and fast programming
language now being used for increasingly complex web development
and beyond!
Comments can explain what the code is doing, leave instructions for
developers using the code, or add any other useful annotations.
There are two types of code comments in JavaScript:
1. A single-line comment will comment out a single line and is
denoted with two forward slashes // preceding it.
2.Multiline comments are denoted by /*…..*/
Datatypes
In javascript they are eight fundamental datatypes.
1.Numbers normal numbers like 1234,123 etc
2.BigInt numbers between 2^-53 to 2^53 like 123456789n
3.String any characters between double or single quotes
preferably single quotes.
4.Boolean True or false
5.Null represents the absence of value and represented by null
without quotes.
6.Undefined this is similar to null but the given value does not
exist. And is represented by keyword undefined without quotes.
7.Symbol a new feature added to the language used as unique
identifiers and used in the complex code.
8.Object collection of related data.
The first seven data types are primitive data types and objects are
used in more complex code.
1
To print something:
console.log(9);……output is 9
console.log(‘Hello World’);
An operator is something which comes very handy in programming.
Arithmetic Operators
This allows us to use basic mathematical operations
Add +
Subtract –
Multiplication *
Division /
Remainder %
It goes like console.log(3 + 4);
String concatenation
When between two strings a plus is used it concatenates as one.
console.log(‘hi’ + ‘ya’)…..prints hiya
the computer will join in the space we leave between the words. So
it must be taken care of
When a new thing is introduced to javascript it saves it to its
browser.
Each data type has few properties which are passed down in
instances.
There is another operator named dot opertator…
console.log(‘Hello’.length)….prints 5
Methods are actions we can perform. So datatypes have access to
various methods that allows us to handle instances of that datatype.
2
We can use these certain methods for instances
1. A period or dot operator
2. Name of the method
3. Closing and opening parenthesis
Consolelog(‘hello’.toUpperCase()) prints HELLO
Consolelog( ‘hey’.startsWith(‘H’)) prints true
Trim() used to remove the spaces at front and back
In javascript there are built in objects console.log(Math.random())
Prints 0 and 1
Math.random is for printing a number between 0 and 1
Math.floor rounds off the number to the closest whole number.
Math.ciel to calculate the smallest integer greater that or equal to
the .isInteger() method from the Number object to check if 2017 is
an integer.
Console.log(Number.isInteger(2017)) prints true
In programming we think variable as containers information is stored
in variables and then found in memory.
It is important to distinguish variable from value
a value is the actual data (like a number, text, or object) that a
variable holds, while a variable is a named storage location in the
computer's memory that stores a value.
There were lot of changes in the context of es6 of javascript it is the
emca sixth edition.
One of the biggest keywords change were let and const…before they
were using only var to declare or use variables.
Javascript uses camel case.
3
Variables cannot start with numbers
Variables cannot have same name as keywords.
Var myName = ‘Arya’;
Console.log(myName);
Let is the keyword introduced in es6. It signals that the variable can
be reassigned a different value later on.
let meal = ‘palak’;
console.log(meal);…..palak
meal = ‘paani’;
console.log(meal);…..paani
let and var keywords if there is no value…it prints undefined.
let meal;
console.log(meal);….undefined
const is also a variable keyword introduced in es6. It is also used to
store values which are constant. If we try reassigning the const
variable to another value it gives typeError.
And if we try to declare and not assign in const then it will show
syntax error.
If something needs to reassigned later on use let or then use const.
Mathematical assignment operators are normal operations as well
has +=,-=,*=,/=,%=…
There are increment and decrement operators.
let myPet = ‘Chuchu’
console.log(‘My pet is ‘ + myPet + ‘.’)
4
In the ES6 version of JavaScript, we can insert, or interpolate
variables into strings using template literals.
A template literal is wrapped by backticks ` (this key is usually
located on the top of the keyboard, left of the 1 key).
Inside the template literal, we’ll see a placeholder, ${myPet}.
The value of myPet is inserted into the template literal.
When we interpolate `I own a pet ${myPet}.`, the output we print
is the string: 'I own a pet armadillo.'
One of the biggest benefits of using template literals is the
readability of the code. Using template literals, we can more easily
tell what the new string will be. We also don’t have to worry about
escaping double quotes or single quotes.
typeof operator helps in finding the datatype of the value
const shi = ‘hihi’
console.log(typeof shi);…..string
conditional operators
if, else if, and else statements
comparison operators
logical operators
truthy vs falsy values
ternary operators
switch statement
if(true){
console.log(‘This message will print’)
if(){
;;;;;;;;;}
5
Else{
;;;;;;;}
Comparison operators:
Less than: <
Greater than: >
Less than or equal to: <=
Greater than or equal to: >=
Is equal to: ===
Is not equal to: !==
Logical operators:
the and operator (&&) two tings are true
the or operator (||) one thing true
the not operator, otherwise known as the bang operator (!)
So which values are falsy, or evaluate to false when checked as a
condition? The list of falsy values includes:
0
Empty strings like "" or ''
null, which represents when there is no value at all
undefined, which represents when a declared variable lacks a
value
NaN, or Not a Number
JavaScript assigns the truthy value to a variable if you use
the || operator in your assignment
let writingUtensil = tool || 'pen'Because ||
6
check the left-hand condition first, the variable defaultName will be
assigned the actual value of username if it is truthy, and it will be
assigned the value of 'Stranger' if username is falsy. This concept is
also referred to as short-circuit evaluation
ternery operators
isNightTime ? console.log('Turn on the lights!') : console.log('Turn off
the lights!');
like if else statements ternery operators can also answer evaluate
true or false
The else if statement always comes after the if statement and
before the else statement. The else if statement also takes a
condition. Let’s take a look at the syntax:
let stopLight = 'yellow';
if (stopLight === 'red') {
console.log('Stop!');
} else if (stopLight === 'yellow') {
console.log('Slow down.');
} else if (stopLight === 'green') {
console.log('Go!');
} else {
console.log('Caution, unknown!');
}
A switch statement provides an alternative syntax that is easier to
read and write. A switch statement looks like this:
let groceryItem = 'papaya';
7
switch (groceryItem) {
case 'tomato':
console.log('Tomatoes are $0.49');
break;
case 'lime':
console.log('Limes are $1.49');
break;
case 'papaya':
console.log('Papayas are $1.29');
break;
default:
console.log('Invalid item');
break;
}
// Prints 'Papayas are $1.29'
An if statement checks a condition and will execute a task if
that condition evaluates to true.
if...else statements make binary decisions and execute different
code blocks based on a provided condition.
We can add more conditions using else if statements.
Comparison operators, including <, >, <=, >=, ===, and !== can
compare two values.
8
The logical and operator, &&, or “and”, checks if both provided
expressions are truthy.
The logical operator ||, or “or”, checks if either provided
expression is truthy.
The bang operator, !, switches the truthiness and falsiness of a
value.
The ternary operator is shorthand to simplify
concise if...else statements.
A switch statement can be used to simplify the process of
writing multiple else if statements. The break keyword stops
the remaining cases from being checked and executed in
a switch statement.
A function is a reusable block of code that groups together a
sequence of statements to perform a specific task.
One way to create a function is by using a function declaration.
Just like how a variable declaration binds a value to a variable
name, a function declaration binds a function to a name, or
an identifier. Take a look at the anatomy of a function
declaration below:
a function declaration binds a function to an identifier.
a function declaration does not ask the code inside the function
body to run, it just declares the existence of the function. The
code inside a function body runs, or executes, only when the
function is called.
Function getGreeting(){
Console.log(“Hello World”)
}
getGreeting()
When declaring a function, we can specify its parameters.
Parameters allow functions to accept input(s) and perform a
9
task using the input(s). We use parameters as placeholders for
information that will be passed to the function when it is called.
When calling a function that has parameters, we specify the
values in the parentheses that follow the function name. The
values that are passed to the function when it is called are
called arguments. Arguments can be passed to the function as
values or variables.
calculateArea(10,6)
function sayThanks(name) {
console.log('Thank you for your purchase, '+ name + ' ! We
appreciate your business.');
}
sayThanks('Cole')
When a function is called, the computer will run through the
function’s code and evaluate the result. By default, the
resulting value is undefined.
To pass back info and not undefined return is used. To create a
return statement, we use the return keyword followed by the
value that we wish to return. Like we saw above, if the value is
omitted, undefined is returned instead.
function monitorCount(rows, columns){
return rows * columns}
const numOfMonitors = monitorCount(5, 4)
console.log(numOfMonitors);
unction monitorCount(rows, columns) {
return rows * columns;
}
function costOfMonitors(rows, columns){
return monitorCount(rows, columns) * 200
10
}
const totalCost = costOfMonitors(5, 4)
console.log(totalCost)
Another way to define a function is to use a function
expression. To define a function inside an expression, we can
use the function keyword. In a function expression, the function
name is usually omitted. A function with no name is called
an anonymous function. A function expression is often stored in
a variable in order to refer to it.
Ananoyms function
variableName(argument1, argument2)
const plantNeedsWater = function(day){
if(day === 'Wednesday')
return true
else
return false
}
console.log(plantNeedsWater('Tuesday'))
ES6 introduced arrow function syntax, a shorter way to write
functions
by using the special “fat arrow” () => notation.
Arrow functions remove the need to type out the
keyword function every time we create a function. Instead, we
first include the parameters inside the ( ) and then add an
arrow => that points to the function body surrounded
in { } like this:
const rectangleArea = (width, height) => {
11
let area = width * height;
return area;
};
Functions that take only a single parameter do not need that
parameter to be enclosed in parentheses. However, if a
function takes zero or multiple parameters, parentheses are
required.
Zero function
Const functionName = () => {}
One function
Const functionName = paramone => {}
Two or more function
Const functionName = (paramone, paramtwo) => {}
A function body composed of a single-line block does not need
curly braces. Without the curly braces, whatever that line
evaluates will be automatically returned. The contents of the
block should immediately follow the arrow =>, and
the return keyword can be removed. This is referred to
as implicit return
1. Function declaration: function greetWorld(){…}
2. Function parameters: function greetWorld(width,
height){
Console.log(…)}
3. Function calling continue of last one greetWorld();
Const area = width * height;
4. To return the function we return area ;
5. Arrow function const calculateArea = (width, height)
=>{
12
Const area = width * height
Return area}
Scope defines where variables can be accessed or referenced.
While some variables can be accessed from anywhere within a
program, other variables may only be available in a specific
context.
Scope refers to where variables can be accessed
throughout the program, and is determined by where and
how they are declared.
Blocks are statements that exist within curly braces {}.
Global scope refers to the context within which variables
are accessible to every part of the program.
Global variables are variables that exist within global
scope.
Block scope refers to the context within which variables
are accessible only within the block they are defined.
Local variables are variables that exist within block
scope.
Global namespace is the space in our code that contains
globally scoped information.
Scope pollution is when too many variables exist in a
namespace or variable names are reused.
Arrays are JavaScript’s way of making lists. Arrays can store
any data types strings, numbers, and booleans). Like lists, arrays
are ordered, meaning each item has a numbered position.
We use dot notation, chaining a period with the property
name to the array, to access the length property of
the newYearsResolutions array.
Then, we log the length of newYearsResolution to the
console.
Since newYearsResolution has two elements, 2 would be
logged to the console.
13
One method, .push(),
allows us to add items to the end of an array.
const groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown rice',
'pasta', 'coconut oil', 'plantains'];
groceryList.shift()
groceryList.unshift('popcorn')
console.log(groceryList)
console.log(groceryList.slice(1, 4))
console.log(groceryList)
const pastaIndex = groceryList.indexOf('pasta')
console.log(pastaIndex)
[
'popcorn',
'bananas',
'coffee beans',
'brown rice',
'pasta',
'coconut oil',
'plantains'
]
[ 'bananas', 'coffee beans', 'brown rice' ]
[
'popcorn',
'bananas',
'coffee beans',
'brown rice',
'pasta',
'coconut oil',
'plantains'
]
4
So when we pass an array into a function, if the array is mutated inside the function, that
change will be maintained outside the function as well. This concept is also sometimes
called pass-by-reference, since what we’re actually passing to the function is a reference
to where the variable is stored in memory and changing the data there.
Arrays are lists that store data in JavaScript.
Arrays are created with brackets [].
Each item within an array is located at a numbered
position, or index, starting at 0.
We can access one item in an array using its index, with
syntax like: myArray[0].
14
We can also change an item in an array using its index,
with syntax like myArray[0] = 'new string';
Arrays have a length property, which allows you to see
how many items are in an array.
Arrays have their own
Preview: Docs Loading link description
methods
, including
Preview: Docs Loading link description
.push()
and
Preview: Docs Loading link description
.pop()
, which add and remove items from an array, respectively.
Arrays have many methods that perform different tasks,
such as .slice() and
Preview: Docs Loading link description
.shift()
, you can find documentation at the Mozilla Developer
Network website.
Some built-in methods are mutating, meaning the method
will change the array, while others are not mutating. You
can always check the documentation.
Preview: Docs Loading link description
Variables
that contain arrays can be declared with let or const. Even
when declared with const, arrays are still mutable. However, a
variable declared with const cannot be reassigned.
Arrays mutated within a function will keep that change
even outside the function.
15
Arrays can be nested inside other arrays.
To access elements in nested arrays, chain indices using
bracket notation.
loop
loop is a programming tool that repeats a set of instructions
until a specified condition, called a stopping condition is
reached
The for loop
Instead of writing out the same code over and over, loops allow
us to tell the computer to repeat a given block of code on its
own. One way to give computers these instructions is with a for
loop.
A for loop contains three expressions separated by ; inside the
parentheses:
1. an initialization starts the loop and can also be used to
declare the iterator variable.
2. a stopping condition is the condition that the iterator
variable is evaluated against — if the condition evaluates
to true, the code block will run. If it evaluates to false, the
code will stop.
3. an iteration statement is used to update the iterator
variable on each loop.
for (let counter = 0; counter < 4; counter++) {
console.log(counter);
}
Loop in reverse
for (let counter = 3; counter >= 0; counter--){
console.log(counter);
}
Output 3210
Nested loop:
16
const arrayA = [6, 19, 20];
const arrayB = [19, 81, 2];
for (let i = 0; i < arrayA.length; i++) {
for (let j = 0; j < arrayB.length; j++) {
if (arrayA[i] === arrayB[j]) {
console.log('Both arrays have the number: ' + arrayB[j]);
}
}
}
While loop:
We start our loop with the keyword while followed by our
stopping condition, or test condition. This will be evaluated
before each round of the loop. While the condition evaluates
to true, the block will continue to run. Once it evaluates
to false the loop will stop.
Do while loop
In some cases, we want a piece of code to run at least once and
then loop based on a specific condition after its initial run. This
is where the do...while statement comes in.
A do while statement says to do a task once and then keep
doing it until a specified condition is no longer met.
let countString = '';
let i = 0;
do {
countString = countString + i;
i++;
} while (i < 5);
17
console.log(countString);
const cupsOfSugarNeeded = 5
let cupsAdded = 0
do {
cupsAdded++
console.log(cupsAdded + 'cup was added')
} while(cupsAdded < cupsOfSugarNeeded)
Output
1cup was added
2cup was added
3cup was added
4cup was added
5cup was added
Break
Break keyword allows you to break out from a loop.
for (let i = 0; i < 99; i++) {
if (i > 2 ) {
break;
}
console.log('Banana.');
}
console.log('Orange you glad I broke out the loop!');
Output
Banana.
Banana.
18
Banana.
Orange you glad I broke out the loop!
Break can be very useful in large data structures of loops.
Higher-order functions are functions that accept other
functions as arguments and/or return functions as output. This
enables us to build abstractions on other abstractions, just like
“We hosted a birthday party” is an abstraction that may build
on the abstraction “We made a cake.”
Stone paper Scissors:
const getUserChoice = (userInput) => {
userInput = userInput.toLowerCase();
if (
userInput === "rock" ||
userInput === "paper" ||
userInput === "scissors" ||
userInput === "bomb"
){
console.log(`User input is ${userInput}`);
return userInput
} else {
console.log("Invalid input!");
return null
}
};
const getComputerChoice = () => {
const randomNumber = Math.floor(Math.random() * 3);
19
if (randomNumber === 0) {
return "rock";
} else if (randomNumber === 1) {
return "paper";
} else {
return "scissors";
}
};
const determineWinner= (userChoice , computerChoice) =>{
if (userChoice === computerChoice) {
return "Tie";
}
if (userChoice === "rock") {
return computerChoice === "paper" ?
"Computer won!" : "User won!"
}
if (userChoice === "paper") {
return computerChoice === "scissors" ? "Computer won!" :
"User won!"
}
if (userChoice === "scissors"){
return computerChoice === "rock" ? "Computer won!" :
"User won!";
};
const cheat = 'bomb'
if(userChoice === cheat){
return "User won!"
20
}
}
function playGame(){
const userChoice = getUserChoice("bomb")
const computerChoice = getComputerChoice()
console.log(`Computer choice is ${computerChoice}`)
console.log(determineWinner(userChoice, computerChoice))
}
playGame()
Scope refers to where variables can be accessed
throughout the program, and is determined by where and
how they are declared.
Blocks are statements that exist within curly braces {}.
Global scope refers to the context within which variables
are accessible to every part of the program.
Global variables are variables that exist within global
scope.
Block scope refers to the context within which variables
are accessible only within the block they are defined.
Local variables are variables that exist within block
scope.
Global namespace is the space in our code that contains
globally scoped information.
Scope pollution is when too many variables exist in a
namespace or variable names are reused.
21
22