0% found this document useful (0 votes)
15K views

Javascript

Uploaded by

Ad Patel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15K views

Javascript

Uploaded by

Ad Patel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Introduction

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

called by appending an instance with a period.the


Math.random():
method name, and parentheses.

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

console. log("howdy'. length);


1/ Prints: 5
Data Instances
When a new piece of data is introduced into a JavaScript
program, the program keeps track of it in an instance of
that data type. An instance is an individual case of a data
type.

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

Single Line Comments


InJavaScript, single-line comments are created with two
1/ This line will denote a comment
consecutive forward slashes //.

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';

Remainder / Modulo Operator


The remainder operator, sometimes called modulo,
1/ calculates # of weeks in a year, rounds
returns the number that remains after the right-hand
number divides into the left-hand number as many
down to nearest integer
=
times as it evenly can. const weeksInYear Math.floor (365/7);

1/ calcuates the number of days left over


after 365 is divded by 7
=
const daysLeftover 365 % 7 ;

console.log("A year has " + weeksInYear + "

weeks and " + daysLeftover + " days");


Assignment Operators
An assignment operator assigns a value to its left = 100;
let number
operand based on the value of its right operand. Here
are some of them:
+= addition assignment 1/ Both statements will add 10
-= subtraction assignment number =
number + 10;
*= multiplication assignment number += 10;
.
/= division assignment

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
+

than the average income. ');


1/ Prints: $85000 is more than the average
income.

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

console.log(`Billy is ${6+8} years old. ):


1/ Prints: Billy is 14 years old.

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' );
}

Logical Operator &&

The logicalAND operator && checks two values and


true && true; || true
returns a boolean. If both values are truthy, then it > 2 && >
returns true.f one, or both, of the values is falsy,
1
2 1; 1/ false
then returns false.
it true && false; 1/ false
4 === 4 && 3 > 1: || true

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'):

1I Prints: 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

the code within its code body executes. if (isMailSent) {


If the expression evaluates to a falsy value, its
console.log('Mail sent to recipient');
code body will not execute. }
Logical Operator !

The logical NOT operator ! can be used to do one of = true;


let lateToWork
the following: =
Invert a Boolean value. let oppositeValue !lateToWork;
• Invert the truthiness of non-Boolean values.

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

Arrow Functions (ES6)


Arrow function expressions were introduced in ES6. two parameters
1/ Arrow function with
These expressions are clean and concise. The syntax for sum =
const (firstParam, secondParam) => {
an arrow function expression does not require the
return firstParam +
function keyword and uses a fat arrow > to secondParam;
separate the parameter(s) from the body. }:
There are several variations of arrow functions:
console.log(sum(2,5) ); I/ Prints: 7
Arrow functions with a single parameter do not
require () around the parameter list.
• Arrow
functions with a single expression can use 1/ ArrOw function with no parameters
the concise function body which returns the const printHello =
() => {
result of the expression without the return
console.log( 'hello' );
keyword.
}:
printHello(): /I Prints: hello

a single parameter
1/ Arrow functions with
= => {
const checkWeight weight
:
console.log( `Baggage weight ${weight}
kilograms.);
}:
checkWeight (25); I/ Prints: Baggage weight :

25 kilograms.

1/ Concise arrow functions


const multiply = => a *
(a, b) b;
console.log(multiply(2, 30)); /I Prints: 60
Functions
Functions are one of the fundamental building blocks in 11 Defining the function:
JavaScript. A function is a reusable set of statements to
perform a task or calculate a value. Functions can be function sum(num1, num2) {

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 () {

for the difference between a named function and an return 'BOOM!';


anonymous function.

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.

1/ Without return, so the function doesn't


output the sum
function sum(num1, num2) {

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.

1/ Calling the function


sum(2, 4); // 6
Scope

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

Block Scoped Variables


Const and let are block scoped variables, meaning const isLoggedIn =
true;
they are only accessible in their block or nested blocks.
In the given code block, trying to print the
== true)
statusMessage using the
console.log() if (isLoggedIn {

const statusMessage =
method will result in a ReferenceError.It is 'User is logged in.';
accessible only inside that if block.

console.log(statusMessage):

1/ Uncaught ReferenceError: statusMessage is


not defined

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);
}

printColor (): // Prints: blue


Arrays

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'):

I/ Adding multiple elements:


=
const numbers [1, 2];
numbers.push(3, 4, 5);

Method.pop()
The .pop() method removes the last element from const ingredients = ['eggs', flour',
an array and returns that element.
'chocolate']:

const poppedIngredient = ingredients.pop():


11 'chocolate'
console.log(ingredients ); / ['eggs'.
'flour']
Mutable
JavaScript arrays are mutable, meaning that the values const names =
['Alice', 'Bob'];
they contain can be changed.
Even if they are declared using Const, the contents
can be manipulated by reassigning internal values or names.push('Carl');
using methods like .push() and pop(). 1/'Alice' 'Bob', 'Carl']

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.

// An array containing different data types


=
const mixedArray [1, 'chicken', false];
Loops

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) {

console.log( `${i}. ${items [i]}*):

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

Looping Through Arrays


An array's length can be evaluated with the .length for (let i = 0; i < array.length; it+){
property. This is extremely helpful for looping through
console.log(array [i]):
arrays, as the .length of
the array can be used as
the stopping condition in the loop.

1/ Output: Every item in the array

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

false. The condition is specified before the loop, and


usually, some variable is incremented or altered in the
while loop body to determine when the loop should let i =
0;
stop.

while (i < 5) {
console.log(i);
it+;
Iterators

Functions Assigned to Variables


In JavaScript, functions are a data type just as strings, =
(number) => {
numbers, and arrays are data types. Therefore,
let plusFive
functions can be assigned as values to variables, but are return number + 5;
different from all other data types because they can be
invoked.
1/f is assigned the value of plusFive
=
let f plusFive;

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}. )

1/ Pass in isEven as the callback function


printMsg(isEven, 4);
1/ Prints: The number 4 is an even number:
True.
Higher-Order Functions
In Javascript, functions can be assigned to variables in
the same way that strings or arrays can. They can be
passed into other functions as parameters or returned
from them as well.
A "higher-order function" is a function that accepts

functions as parameters and/or returns a function.

JavaScript Functions: First-Class Objects


JavaScript functions are first-class objects. Therefore: a
1IAssign function to a variable
They have built-in properties and methods, such
as the name property and the
originalFunc
.toString() method. const originalFunc = (num) => { return num +
• Properties and methods can be added to them. 2 }:
They can be passed as arguments and returned
from other functions.
//Re-assign the function to a new variable
They can be assigned to variables, array
elements, and other obje cts. newFunc
=
const newFunc originalFunc;

1/Access the function's name property


newFunc.name; l/'originalFunc'

1/Return the function's body as a


string
num
newFunc. toString(); 1/' (num) => { return
+ 2 }'

1/Add our own isMathFunction property to the


function
= true;
newFunc.isMathFunction

1/Pass the function as an argument


const functionNameLength = (func) => { return
func. name.length };
functionNameLength(originalFunc); //12

I/Return the function


const returnFunc = () => { return newFunc };
returnFunc (); //[Function: originalFunc]
The .reduce() Method
The .reduce() method iterates through an array const arrayofNumbers =
[1, 2, 3, 4]:
and returns a single value.
In the above code example, the .reduce() method
=
will sum up all the elements of the array. It takes a Const sum
callback function with two parameters arrayOfNumbers. reduce( (accumulator,
(accumulator, currentValue) as arguments. currentValue) => {
On each iteration, accumulator is the value
return accumulator + currentValue;
returned by the last iteration, and the
currentValue is the current element. Optionally, a });
second argument can be passed which acts as the initial
value of the accumulator. console.log(sum); // 10

The .forEach() Method


The .forEach() method executes a callback const numbers =
[28, 77, 45, 99, 27];
function on each of the elements in an array in order.
In the above example code, the callback function
numbers.forEach(number => {
containing a console.log() method will be
executed 5 times, once for each element. console.log(number);
}):

The .filter() Method


The .filter() method executes a callback function const randomNumbers =
[4, 11, 42, 14, 39]:
on each element in an array. The callback function for =
const filteredArray randomNumbers. filter (n
each of the elements must return either true or
=> {
false.The returned array is a new array with any
return n > 5;
elements for which the callback function returns
true }):
In the above code example, the array
filteredArray will contain all the elements of
randomNumbers but 4.
The .map() Method
The .map() method executes a callback function on const finalParticipants =
['Taylor',
each element in an array. It returns a new array made up
'Donald" 'Don', 'Natasha 'Bobby']:
of the return values from the callback function.
The original array does not get altered, and the returned
array may contain different elements than the original 1/ add string after each final participant
array.
In
const announcements =
the example code above, the .map() method is
used to add joined the contest. string at finalParticipants .map(member => {

the end of each element in the return member + joined the contest.';
finalParticipants array.

;
console.log(announcements)
Objects

Restrictions in Naming Properties


JavaScript object key names must adhere to some 1/ Example of invalid key names
restrictions to be valid. Key names must either be strings = {
or valid identifier or variable names (i.e. special const trainSchedule
characters such as - are not allowed in key names that platform num: 10, // Invalid because of the
are not strings). space between words.
40 - 10 + 2: 30, /7 Expressions cannot be
keys.
+compartment: 'C' / The use
of a + sign is
invalid unless it is enclosed in quotations.

Dot Notation for Accessing Object Properties


Properties of a JavaScript object can be accessed using const apple = {
the dot notation in this manner:
object.propertyName
.
Nested properties of an color: 'Green',
price: {
object can be accessed by chaining key names in the
Correct order. bulk: $3/kg',
smallQty: '$4/kg'

console.log(apple. color) ; 11 'Green'


console. log(apple.price.bulk); // '$3/kg'

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(classElection .place); //


undefined

JavaScript Objects are Mutable


JavaScript objects are mutable, meaning their contents const student = {
can be changed, even when they are declared as
const .New properties can be added, and existing
name: 'Sheldon',
property values can be changed or deleted. SCore: 100.
It is the reference to the object, bound to the variable, grade: 'A',
that cannot be changed.

console.log(student)
1|{ name: 'Sheldon', score: 100, grade: 'A'
}

delete student. score


=
student.grade 'F'
console.log(student)
1{name: 'Sheldon', grade: 'F' }

student = }
1/ TypeError: Assignment to constant
variable.

JavaScript for...in loop


The JavaScript for...in loop can be used to iterate let mobile = {
over the keys of an object.In each iteration, one of the
brand: 'Samsung'
properties from the object is assigned to the variable of
that loop. model: 'Galaxy Note 9'
}:

{
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"
};

delete person.hobby; // or delete


person [hobby] :

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);

1/ Will output 8 since integers are passed by


value.
;
console.log(origNum)

1/ Will output 'red' since objects are passed


1/ reference and are therefore mutable.
by
console. log (origobj.color ):
JavaScript Object Methods
JavaScript objects may have property values that are const engine = {
functions. These are referred to as object methods.
Methods may be defined using anonymous arrow
1/ method shorthand, with one argument
function expressions, or with shorthand method syntax. start (adverb) {
Object methods are invoked with the syntax: console.log( The engine starts up
objectName .methodName(arguments).
${adverb}...);
}

1/ anonymous arrow function expression with


no arguments
sputter: () => {

console.log('The engine sputters... ');


}

engine. start( 'noisily' );


:
engine.sputter()

/* Console output:
. .
The engine starts up noisily.
The engine sputters..
*/

JavaScript destructuring assignment shorthand syntax


The JavaScript destructuring assignment is a shorthand const rubiksCubeFacts = {
syntax that allows object properties to be extracted into
possiblePermutations:
specific variable values.
It uses a pair of curly braces ({}) with property names '43,252,003,274,489,856,000',
on the left-hand side of an assignment to extract values
invented: 1974',
from objects. The number of variables can be less than
largestCube: '17x17x17"
the total properties of an object.
}:
const {possiblePermutations, invented,
=
largestCube} rubiksCubeFacts;
console.log(possiblePermutations); //
'43,252,003,274,489,856,000"
console.log(invented); /I 1974"
console.log(largestCube); 11 17x17×17'
shorthand property name syntax for object creation
The shorthand property name syntax in JavaScript allows const activity =
'Surfing':
creating objects without explicitly specifying the
property names lie. explicitly declaring the value after const beach = { activity };
the key). In this process, an object is created where the console.log(beach); 1/ { activity: 'Surfing'
property names of that object match variables which
already exist in that context. Shorthand property names
populate an object with a key matching the identifier and
a value matching the identifier's value.

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

javascript function this


Every Java Script function or method has a this Const restaurant = {
context. For a function defined inside of an object,
numCustomers: 45,
this will refer to that object itself. For a function
defined outside of an object, will refer to the seatCapacity: 100,
this
global object ( Window in a browser, global in availableSeats () {
Node.js).
1/ this refers to the restaurant object
1/ and it's used to access its properties
-
return this.seatCapacity
this.numCustomers;
JavaScript Arrow Function this Scope
JavaScript arrow functions do not have their own this const myObj = {
context, but use the thiS of the surrounding lexical
data:'abc',
context. Thus, they are generally a poor choice for
writing object methods. loggerA: () => { console. log(this. data) ;

Consider the example code: }.


loggerA is a property that uses arrow notation to loggerB() {
console. log( this.data); },
define the function. Since data does not exist in the
};
global context, accessing this. data returns
undefined
loggerB uses method syntax. Since this refers to myObj.loggerA(): 1/ undefined
the enclosing object, the value of the data property is myObj.loggerB(): 1/ 'abc!
accessed as expected, returning "abc"

getters and setters intercept property access


JavaScript getter and setter methods are helpful in part const myCat = {
because they offer a way to intercept property access
name: 'Snickers'
and assignment, and allow for additional actions to be
performed before these changes go into effect. get name(){
return this. name
}

set name (newName){

I/Verify that newName is a non-empty


string before setting as name property
if (typeof newName =*= 'string &&

newWame.length > 0){


= newName;
this.name
} {
else
console.log("ERROR: name must be a non
empty string");
javascript factory functions
A JavaScript function that returns an object is known as a
1/ A factory function that accepts 'name'
factory function. Factory functions often accept
parameters in order to customize the returned object. 1/ 'age', and 'breed' parameters to return
1/ a customized dog object.
const dogFactory = (name, age, breed) > {
return {

name: name,
age: age,
breed: breed,
bark() {
console.log('Woof!');

}:

javascript getters and setters restricted


JavaScript object properties are not private or const my
Cat = {
protected. Since JavaScript objects are passed by
name : 'Dottie',
reference, there is no way to fully prevent incorrect
interactions with object properties. get name() {

One way to implement more restricted interactions with return this._name;


object properties is to use getter and setter methods.
}
Typically, the internal value is stored as a property with
an identifier that matches the getter and setter method set name (newName) {
names, but begins with an underscore (_). name = newName;
this.

}:

1/ Reference invokes the getter


console.log(myCat.name);

11 Assignment invokes the setter


my =
Cat.name 'Yankee':

You might also like