Javascript
Javascript
console.log()
The console. log() method is used to log or print console.log( 'Hi there!");
messages to the console. It can also be used to print
objects and other info.
1/ Prints: Hi there!
JavaScript
JavaScript is a programming language that powers the
dynamic behavior on most websites. Alongside HTML and
CSS, it is a core technology that makes the web run.
Methods
Methods return information about an object, and are 1/ Returns a number between 0 and 1
Built-in Objects
Built-in objects contain methods that can be called by Math.random():
appending the object name with a period the
method name, and a set of parentheses.
1/Math is the built-in object
Numbers
Numbers are a primitive data type. They include the set =
let amount 6;
of all integers and floating point numbers. =
let price 4.99;
String .length
The .length property of a string returns the number let message = 'good nite':
of characters that make up the string.
console. log(message. length);
1/ Prints: 9
Booleans
Booleans are a primitive data type. They can be either let lateToWork = true;
true or false.
Math.random()
The Math.random() method returns a floating console. log(Math.random( ));
point, random number in the range from 0 (inclusive) up
1/ Prints: 0 - 0.9999999999999999
to but not including 1.
Math.floor()
The Math.floor() function returns the largest console.log(Math.floor (5.95));
integer less than or equal to the given number.
1/ Prints: 5
Null
Null is a primitive data type. It represents the intentional x = null;
let
absence of value. In code, it is represented as null,
Strings
Strings are a primitive data type. They are any grouping = my
let single 'Wheres bandit hat?':
of characters (etters, spaces, numbers, or symbols) = my
surrounded by single quotes or double quotes let double "Wheres bandit hat?";
Arithmetic Operators
JavaScript supports arithmetic operators for: 1/ Addition
+ addition
5 + 5
subtraction
* multiplication 1/ Subtraction
/ division 10 - 5
% modulo 1/ Multiplication
5* 10
1/ Division
10 / 5
// Modulo
10 % 5
Multi-line Comments
InJavaScript, multi-line comments are created by
surrounding the lines with /* at the beginning and
The below configuration must be
*/ at the end. Comments are good ways for a variety
of reasons like explaining a code block or indicating changed before deployment.
some hints, etc. */
=
let baseUrl 'localhost/taxwebapp/country';
console.log(number);
1/ Prints: 120
String Interpolation
String interpolation is the process of evaluating string
let age =
7;
literals containing one or more placeholders
(expressions, variables, etc).
It can be performed using template literals: text 1/ String concatenation
${expression} text. 'Tommy is + age + years old. ':
1/ String interpolation
Tommy is ${age} years old.';
Variables
Variables are used whenever there's a need to store a const urrency =
'$';
piece of data. A variable contains data that can be used
=
in the program elsewhere. Using variables also ensures let userIncome 85000;
code re-usability since it can be used to replace the
same value in multiple places.
console.log(currency userIncome + is more
+
Undefined
undefined is a primitive JavaScript value that var a;
represents lack of defined alue. Variables that are
declared but not initialized to a value will have the value
;
undefined console.log(a)
1/ Prints: undefined
Learn Javascript: Variables
A variable is a container for data that is stored in
1/ Examples of variables
computer memory. It is referenced by a descriptive
let ame = "Tammy";:
name that a programmer can call to assign a specific
value and retrieve it. const found = false;
var age = 3;
console .log(name, found, age);
1/ Prints: Tammy false 3
Declaring Variables
To declare a variable in JavaScript, any of these three var age;
keywords can be used along with a variable name:
var is used in pre-ES6 versions of JavaScript. let weight;
const number0fFingers =
•
let is the preferred way to declare a variable 20;
when it can be reassigned.
Const is the preferred way to declare a
variable with a constant value.
Template Literals
Template literals are strings that allow embedded let name = "Codecademy";
expressions, ${expression}.While regular strings
console.log(`Hello, ${name}`);
use single or double quotes, template literals use
backticks instead. 1/ Prints: Hello, Codecademy
let Keyword
let creates a local variable in JavaScript & can be re let count;
assigned. Initialization during the declaration of a let
variable is optional. A
console.log(count ); /I Prints: undefined
letvariable will contain
COunt =
10;
undefined if nothing is assigned to it.
console.log(count); // Prints: 10
const Keyword
Aconstant variable can be declared using the keyword const number0fColumns = 4;
const .It must have an assignment. Any attempt of re number0fColumns = 8;
assigning a const variable will result in JavaScript
runtimne error. 1/ TypeError: Assignment to constant
variable.
String Concatenation
In JavaScript, multiple strings can be concatenated =
let service 'credit card';
together using the t operator. In the example, multiple = 'May
strings and variables containing string values have been let month 30th';
concatenated. After execution of the code block, the let displayText = 'Your' +
service +
' bi1l
displayText variable will contain the concatenated is due on ' + month + '.';
string.
console.log(displayText ) ;
1/ Prints: Your credit card bill is due on
May 30th.
Conditionals
Control Flow
Control flow is the order in which statements are
executed in a program. The default control flow is for
statements to be read and executed in order from left
to-right, top-to-bottom in a program file.
Control structures such as conditionals ( if statements
and the like) alter control flow by only executing blocks
of code if certain conditions are met. These structures
essentially allow a program to make decisions about
which code is executed as the program runs.
Logical Operator | |
The logical OR operator || checks two values and true | | false; 1/ true
returns a boolean. If one or both values are truthy, it > 5 10 >
10 || 20; 1/ true
returns true.If both values are falsy, it returns
false. false || false; 1/ false
A B
10 > 100 || 10 > 20; 1/ false
A B
||
false false false
false true true
true false true
true true true
Ternary Operator
The ternary operator allows for a compact syntax in the =
case of binary (choosing between two choices) decisions.
let price 10.5;
=
Itaccepts a condition followed by a ? operator, and let day "Monday":
then two expressions separated by a :.If the condition
evaluates to truthy, the first expression is exe cuted, day === "Monday" ? price -= 1.5 :
price +=
otherwise, the second expression is executed.
1.5;
else Statement
An else block can be added to an if block or series const isTaskCompleted =
false;
of -
if else if blocks. The else block will be
executed only if the if condition fails.
if (isTaskCompleted) {
console.log('Task completed');
} else {
console.log('Task incomplete' );
}
switch Statement
The SWitch statements provide a means of checking const food = 'salad';
an expression against multiple case clauses. If a case
matches, the code inside that clause is executed.
switch (food) {
The case clause should finish with a break
keyword. If no case matches but a clause is
default case 'oyster':
included, the code inside default will be executed. console.log('The taste of the sea ');
Note: If break is omitted from the block of a case,
break;
the switch statement will continue to check against
case 'pizza':
case values until a break is encountered or the flow is
broken. console.log("A delicious pie '):
break;
default:
console.log('Enjoy your meal'):
if Statement
An 1f statement accepts an expression with a set of const isMailSent = true;
parentheses:
If the expression evaluates to a truthy value, then
console.log(oppositeValue);
1/ Prints: false
Comparison Operators
Comparison operators are used to comparing two values 1>3 1/ false
and return true or falsedepending on the
validity of the comparison:
3 > 1
I/ true
strict equal 250 >= 250 1/ true
== strict not equal 1 === 1
1/ true
> greater than 1 == 2 1/ false
>= greater than or equal ===
1
1' 1/ false
< less than
<= less than or equal
else if Clause
After an initial if block, else if blocks can each const size = 10;
check an additional condition. An optional else block
can be added after the else if block(s) to run by
> 100) {
default if none of the conditionals evaluated to truthy. if (size
console.log('Big'):
} > 20) {
else if (size
console.log('Medium' );
} > 4) {
else if (size
console.log('Small');
} else {
console. log('Tiny');
1/ Print: Smal1
Truthy and Falsy
JavaScript, values evaluate to
In
true or false
when evaluated as Booleans.
Values that evaluate to true are known as
truthy
• Values that evaluate to false are known as
falsy
Falsy values include false, 0, empty strings, null
undefined. and NaN. All other values are truthy.
Functions
a single parameter
1/ Arrow functions with
= => {
const checkWeight weight
:
console.log( `Baggage weight ${weight}
kilograms.);
}:
checkWeight (25); I/ Prints: Baggage weight :
25 kilograms.
passed one or more values and can return a value at the return num1 + num2;
end of their execution. In order to use a function, you
must define it somewhere in the scope where you wish
to call it.
The example code provided contains a function that / Calling the function:
takes in 2 values and returns the sum of those numbers. sum(3, 6); // 9
Anonymous Functions
Anonymous functions in JavaScript do not have a name
1/ Named function
property. They can be defined using the function
keyword, or as an arrow function. See the code example
function rocketToMars () {
1/ Anonymous function
=
const rocketToMars function() {
return 'BOOM!';
Function Expressions
Function expressions create functions inside an const dog =
function () {
expression instead of as a function declaration. They can
be anonymous and/or assigned to a variable.
return "Woof!':
Function Parameters
Inputs to functions are known as parameters when a 11 The parameter name
is
function is declared or defined. Parameters are used as
function sayHello (name) {
variables inside the function body. When the function is
called, these parameters will have the value of whatever return Hello, ${name}!;
is passed in as arguments. It is possible to define a
function without parameters.
return Keyword
Functions return (pass back) values using the return 1/ With return
keyword. return ends function execution and function sum(num1, num2 ) {
returns the specified value the location where it was
called. A common mistake is to forget the return return num1 +t num2;
keyword, in which case the function will return
undefined by default.
num1 + num2;
Function Declaration
Function declarations are used to create named function add(num1, num2) {
functions. These functions can be called using their
declared name. Function declarations are built from: return num1 + num2;
The function keyword.
.
The function name.
• An opional list of parameters separated by
commas enclosed by a set of parentheses )
A function body enclosed in a set of curly braces
{}.
Calling Functions
Functions can be called, or executed, elsewhere in code
using parentheses following the function name. When a
1/ Defining the function
function is called, the code inside its function body runs.
function sum(num1, num2) {
Arguments are values passed into a function when it is return num1 + num2;
called.
Scope
Scope is a concept that refers to where values and {
function myFunction()
functions can be accessed.
Various scopes include:
Global scope la value/function in the global var pizzaName = "Volvo";
scope can be used anywhere in the entire
program)
1/ Code here can use pizzaName
•
File or module scope (the value/function can
only be accessed from within the file)
Function scope (only visible within the function),
Code block scope (only visible withina {
}
codeblock)
1/ Code here can't use pizzaName
const statusMessage =
method will result in a ReferenceError.It is 'User is logged in.';
accessible only inside that if block.
console.log(statusMessage):
Global Variables
JavaScript variables that are declared outside of blocks
1/ Variable declared globally
or functions can exist in the global scope, which means
they are accessible throughout a program. Variables
const color = 'blue':
declared outside of smaller block or function scopes are
accessible inside those smaller scopes. {
function printColor()
Note: It is best practice to keep global variables to a
minimum.
console. log(color);
}
Property .length
The .length property of a JavaScript array indicates const numbers =
[1, 2, 3, 4]:
the number elements the array contains.
of
numbers.length 1/4
Index
Array elements are arranged by index values, starting at an array element
1/ Accessing
0 as the first element index. Elements can be accessed =
by their index using the array name, and the index
const myArray [100, 200, 300]:
surrounded by square brackets.
console.log(myArray [0] ) ; // 100
console.log(myArray [1] ); // 200
console.log(myArray[2] ): // 300
Method .push()
The .push() method of JavaScript arrays can be 1/ Adding a single element:
to
used add one or more elements to the end of an =
const cart ['apple', 'orange'];
array. .push() mutates the original array and returns
the new length of the array. cart.push('pear'):
Method.pop()
The .pop() method removes the last element from const ingredients = ['eggs', flour',
an array and returns that element.
'chocolate']:
Arrays
Arrays are lists of ordered, stored data. They can hold
items that are of any data type. Arrays are created by
1/ An array containing numbers
const numberArray =
using square brackets, with individual elements
[0, 1, 2, 3];
separated by commas.
Reverse Loop
A for loop can iterate "in reverse" by initializing the
const items =
['apricot', 'banana',
loop variable to the starting value, testing for when the
variable hits the ending value, and decrementing 'cherry']:
(subtracting from) the loop variable at each iteration.
for (let i =
items. length - 1; i >= 0; i -=
1) {
1/ Prints: 2. cherry
1/ Prints: 1. banana
1/ Prints: 0. apricot
Do...While Statement
A do.. .while statement creates a loop that X = 0
exe cutes a block of code once, checks if a condition is
= 0
true, and then repeats the loop as long as the condition i
is true. They are used when you want the code to always
execute at least once. The loop ends when the condition do {
evaluates to false.
X = i;X +
console.log(x)
i++;
} <
while (i 5);
1/ Prints: 0 1 3 6 10
For Loop
=
A
for loop declares looping instructions, with three for (let i 0; i < 4; i += 1) {
important pieces of information separated by
console.log(i):
semicolons ;:
The initialization defines where to begin the loop };
by declaring (or referencing) the iterator variable
The stopping condition determines when to stop
looping (when the expression evaluates to
1/ Output: 0, 1, 2, 3
false )
The iteration statement updates the iterator
each time the loop is completed
Break Keyword
Within a loop, the break keyword may be used to exit for (let i
=
0; i <
99; i += 1) {
the loop immediately, continuing execution after the
if (i > 5) {
loop body.
Here, the break keyword is used to exit the loop break:
when l is greater than 5.
console. log(i)
}
1/ Output: 0 1 2 3 4 5
Nested For Loop
A nested for loop is when a for loop runs inside for (let outer = 0; outer < 2; outer t= 1) {
another for loop.
The inner loop willrun allits iterations for each iteration
for (let inner = 0; inner < 3; inner += 1)
of the outer loop.
console.log(`${outer}-${inner}'):
/*
Output:
0-0
0-1
0-2
1-0
1-1
1-2
*/
Loops
A loop is a programming tool that is used to repeat a set
of instructions. Iterate is a generic term that means "to
repeat" in the context of loops. A loop will continue to
iterate until a specified condition, commonly known as a
stopping condition, is met.
While Loop
The While loop creates a loop that is executed as long while (condition) {
as a specified condition evaluates to true. The loop
1| code block to be executed
will continue to run until the condition evaluates to
while (i < 5) {
console.log(i);
it+;
Iterators
plusFive(3); // 8
1/ Since f has a function value, it can be
invoked.
f(9); 1| 14
Callback Functions
InJavaScript, a callback function is a function that is const isEven =
(n) => {
passed into another function as an argument. This
return n % 2 == 0;
function can then be invoked during the execution of
that higher order function (that it is an argument of).
Since, in JavaScript, functions are objects, functions can
be passed as arguments.
let printMsg = (evenFunc, num) => {
const isNumEven = evenFunc (num);
console.log( The number ${num} is an even
number: ${isNumEven}. )
the end of each element in the return member + joined the contest.';
finalParticipants array.
;
console.log(announcements)
Objects
Objects
An object is a built-in data type for storing key-value
pairs. Data inside objects are unordered, and the values
can be of any type.
Accessing non-existent JavaScript properties
When trying to access a JavaScript object property that const classElection = {
has not been defined yet, the value of undefined
willbe returned by default.
date: ' January 12'
};
console.log(student)
1|{ name: 'Sheldon', score: 100, grade: 'A'
}
student = }
1/ TypeError: Assignment to constant
variable.
{
for (let key in mobile)
console.log('${key}: ${mobile [key ]}');
Properties and values of a JavaScript object
A JavaScript object literal is enclosed with curly braces = {
const class0f2018
}. Values are mapped to keys in the object with a
colon (: ), and the key-value pairs are separated by
students: 38,
commas. All the keys are unique, but values are not. year: 2018
Key-value pairs of an object are also referred to as
properties.
Delete operator
Once an object is created in JavaScript, it is possible to Const person = {
remove properties from the object using the
delete firstName: "Matilda",
operator. The delete keyword deletes both the value
of the property and the property itself from the object.
age: 27,
The delete operator only works on properties, not hobby: "knitting",
on variables or functions.
goal: "learning JavaScript"
};
console.log(person);
/*
firstName: "Matilda"
age: 27
goal: "learning JavaScript"
*/
javascriptpassing objectsas arguments
When Java Script objects are passed as arguments to const origNum = 8;
functionsor methods, they are passed by reference, not =
by value. This means that the object itself (not a copy) is
const origObj {color: 'blue'}:
accessible and mutable (can be changed) inside that
function. const changeItUp = (num, obj) => {
num = 7;
=
obj.color 'red':
changeItUp(origNum, orig0bj);
/* Console output:
. .
The engine starts up noisily.
The engine sputters..
*/
this Keyword
The reserved keyword this refers to a method's Const cat = {
calling object, and it can be used to access properties name: 'Pipey',
belonging to that object.
Here, using the this keyword inside the object age: 8,
function to refer to the Cat object and access its whatName() {
name property.
return this.name
console.log(cat.whatName()):
1/ Output: Pipey
name: name,
age: age,
breed: breed,
bark() {
console.log('Woof!');
}:
}: