Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Javascript basic data type ,loop, Summaries of Javascript programming

Learn Javascript basic programming and functional

Typology: Summaries

2022/2023

Uploaded on 08/10/2023

ad-patel
ad-patel 🇮🇳

1 document

1 / 31

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Introduction
console.log()
The console. log() method is used to log or print
messages to the console. It can also be used to print
objects and other info.
JavaScript
JavaScript is aprogramming language that powers the
dynamic behavior on most websites. Alongside HTML and
CSS, it is acore technology that makes the web run.
Methods
Methods return information about an object, and are
called by appending an instance withaperiod.the
method name, and parentheses.
Built-in Objects
Built-in objects contain methods that can be called by
appending the object name with aperiod the
method name, and aset of parentheses.
Numbers
Numbers are aprimitive data type. They include the set
of all integers and floating point numbers.
String .length
The .length property of astring returns the number
of charactersthat make up the string.
console.log( 'Hi there!");
1/ Prints: Hi there!
1/ Returns anumber between 0and 1
Math.random():
Math.random():
1/Math is the built-in object
let amount =6;
let price =4.99;
let message ='good nite':
console. log(message. length);
1/Prints: 9
console. log("howdy'. length);
1/ Prints: 5
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f

Partial preview of the text

Download Javascript basic data type ,loop and more Summaries Javascript programming in PDF only on Docsity!

Introduction

console.log()

The

console.

log()

method

is used

to log

or

print

messages to

the console.

It

can

also be

used

to print

objects

and other

info.

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

called by appending

an

instance

with

a

period.the

method

name,

and

parentheses.

Built-in

Objects

Built-in objects contain methods that

can

be called by

appending the object

name with

a

period the

method

name,

and

a

set of parentheses.

Numbers

Numbers

are

a

primitive data

type. They include the

set

of all integers and floating point numbers.

String

.length

The

.length

property of

a

string returns

the number

of characters that

make

up

the

string.

console.log(

'Hi

there!");

1/ Prints:

Hi

there!

1/ Returns

a
number
between

0

and

1

Math.random():
Math.random():

1/Math is

the

built-in

object

let

amount

=

let

price

=

let

message

=

'good

nite':

console. log(message.

length);

1/ Prints:

9

console.

log("howdy'. length);

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

true

or

false.

Math.random()

The

Math.random()

method

returns

a

floating

point, random number

in the

range

from 0

(inclusive)

up

to but

not including

Math.floor()

The

Math.floor()

function

returns the largest

integer less than

or

equal

to the

given number.

Single Line

Comments

In JavaScript, single-line comments

are

created

with two

consecutive forward slashes

Null

Null is

a

primitive data type.

It

represents

the

intentional

absence of value.

In

code, it

is represented

as

null,
Strings

Strings

are

a

primitive data

type. They

are any

grouping

of characters (etters,

spaces,

numbers,

or symbols)

surrounded

by single quotes

or

double

quotes

let lateToWork

=

true;

console.

log(Math.

random(

Prints:

0

console.log(Math.floor (5.95));

1/ Prints:

5

1/ This line will denote
a
comment

let

x

=

null;

let

single

=

'Wheres

my

bandit hat?':

let

double

=

"Wheres

my

bandit

hat?";

Assignment Operators

An assignment operator assigns

a

value

to its left

operand based

on

the

value of its right operand. Here

are some of them:

+=

addition assignment

subtraction assignment

*=

multiplication assignment

.

division assignment

String Interpolation

String interpolation is the

process of evaluating string

literals containing

one or more placeholders

(expressions, variables, etc).

It can

be performed

using template

literals:

text

${expression}

text.

Variables

Variables

are

used whenever there's

a

need

to store

a

piece of data.

A

variable contains data that

can

be used

in the

program

elsewhere.

Using variables also

ensures

code

re-usability since

it

can

be used

to replace the

same value

in multiple places.

Undefined

undefined

is

a

primitive JavaScript value that

represents lack of defined

alue.
Variables that

are

declared but

not initialized

to

a

value

will have the value

undefined

let

number

=

Both

statements

will

add
number

=

number
number

+=

console.log(number);

1/ Prints:

let

age

=

String

concatenation

'Tommy is

age +

1/ String interpolation

Tommy

is

${age}

years

old.';

const urrency

=

let

userIncome

=

years

old. ':

console.log(currency
userIncome

than the

average

income.

var a;

1/

Prints:

is

more

than

the

average

income.
console.log(a)

;

1/ Prints:

undefined

is

more
Learn
Javascript:
Variables

A variable is

a

container

for data that

is stored

in

computer

memory. It is

referenced by

a

descriptive

name

that

a programmer can

call to assign

a

specific

value and retrieve

it.

Declaring Variables

To declare

a

variable

in JavaScript,

any

of

these three

keywords

can

be used along with

a

variable

name:

var is

used

in pre-ES6 versions of JavaScript.

let

is

the preferred

way

to declare

a

variable

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

expressions,

${expression}.While

regular

strings

quotes, template

literals

use use

single

or

double

backticks instead.

let

Keyword
let
creates

a

local variable

in JavaScript

& can

be

re

assigned. Initialization during

the

declaration of

a

let

variable

is optional.

A

let

variable

will contain

undefined

if nothing

is assigned to

it.

const

Keyword

A constant variable

can

be declared using the

keyword

const

.It

must have an assignment.

Any attempt of

re

assigning

a

const

variable

will result

in JavaScript

runtimne

error.

Examples

of variables

let

ame = "Tammy";:

const

found

=

false;

var age

=

console

.log(name, found, age);

Prints:

Tammy

false

3

var

age;

let

weight;

const number0fFingers

=

let

name

=

"Codecademy";

console.log( Hello, ${name});

1/

Prints:

Hello,

Codecademy
console.log(`Billy

is

years

old.

Prints:

Billy

is

years

old.

let count;

console.log(count

/I

Prints:

undefined

COunt

=

console.log(count);

// Prints:

10

const

number0fColumns

=

number0fColumns

=

1/ TypeError: Assignment

to

constant

variable.

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

returns

a

boolean.

If one or both values

are truthy, it

returns

true.If

both values

are falsy, it returns

false.

A

false
false
true
true

B

false
true

false

true
Ternary Operator

A

B

false
true
true
true

The

ternary operator allows

for

a

compact

syntax in the

case

of binary (choosing between

two choices) decisions.

It accepts

a

condition followed

by

a

operator, and

then

two expressions separated by

a

:.If
the

condition

evaluates

to truthy,

the

first expression

is

exe

cuted,

otherwise, the second

expression

is

executed.

true | |

false;

10

5

10

false

|| false;

10

let

price

=

let

day

=

"Monday":

1/ true

1/ true

1/ false

1/ false

day

===

"Monday"
price

:

price

+=

else Statement

An

else

block

can

be added

to

an

if

block

or

series

of

if

else if

blocks. The

else

block

will

be

executed

only

if

the

if

condition

fails.

Logical Operator

&&

The logical

AND operator

&&

checks

two values and

returns

a

boolean.

If

both values

are truthy, then

it

returns

true.f

one, or

both,

of the

values is falsy,

then

it

returns

false.

switch Statement

The

SWitch

statements provide

a means

of checking

an

expression against multiple case clauses.

If

a case

matches, the code

inside that

clause is executed.

The

case

clause should

finish with

a

break

keyword.

If no case

matches but

a

default

clause

is

included, the code inside

default

will be executed.

Note:

If

break

is omitted from the

block of

a

case,
the

switch

statement will continue

to check against

case

values

until

a

break

is encountered

or

the

flow is

broken.

if

Statement

An

1f

statement accepts

an

expression

with

a set of

parentheses:

If

the

expression evaluates

to

a

truthy value, then

the code

within its code

body executes.

If

the

expression evaluates

to

a falsy value,

its

code

body

will not execute.

const isTaskCompleted

=

false;

if

(isTaskCompleted)

{

console.log('Task completed');

}

else

{

}

console.log('Task incomplete' );

true

&&

true;

1

2

&& 2

true

&&

false;

===

&& 3

switch

(food)

{

const food

=

'salad';

case

'oyster':

}

break;

case

'pizza':
console.log('The

taste of

the

sea

||

true

break;

1/ false

default:

1/ false

||

true

console.log("A

delicious

pie '):

if

(isMailSent)

{

console.log('Enjoy
your
meal'):
1I

Prints:

Enjoy
your
meal

const

isMailSent

=

true;

console.log('Mail sent to recipient');

Truthy and

Falsy

In

JavaScript,

values evaluate

to

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,

empty strings,

null

undefined.

and NaN.

All other values

are truthy.

Functions

Arrow

Functions

(ES6)

Arrow function

expressions

were

introduced

in ES6.

These

expressions

are

clean and concise. The

syntax for

an arrow

function

expression does

not require the

function

keyword and

uses

a

fat

arrow

to

separate the

parameter(s) from the

body.

There

are several variations of

arrow

functions:

Arrow functions

with

a

single parameter do

not

require () around the

parameter list.

Arrow functions

with

a

single expression

can use

the

concise function body which

returns

the

result

of the

expression without the

return

keyword.

Arrow

function with

two parameters

const

sum

=

(firstParam, secondParam)

=>

{

return

firstParam

secondParam;

}:

console.log(sum(2,5)

I/ Prints:

7

ArrOw

function with

no

parameters

const printHello

=

=> {

}:

console.log(

'hello'

)

;

printHello():

/I Prints: hello

1/

Arrow

functions with

a
single

parameter

const checkWeight

=

weight

=> {

console.log( `Baggage weight

:

${weight}
kilograms.);

}:

checkWeight

I/

Prints:

Baggage

weight

:

kilograms.
Concise
arrow

functions

const multiply

=

(a, b)
=> a
b;
console.log(multiply(2, 30));

/I Prints:

return

Keyword

Functions return (pass back) values using

the

return

keyword.

return

ends function execution and

returns

the

specified value the

location where it

was

called.

A

common

mistake

is to forget the

return

keyword,

in which

case

the

function

will return

undefined

by default.

Function Declaration

Function declarations

are

used

to create named

functions. These functions

can

be called using their

declared

name.

Function declarations

are built from:

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

function

is called, the code inside its function body

runs.

Arguments

are

values passed into

a

function when

it is

called.

1/ With return

function

sum(num1,

num2 )

{

return

num

+t

num2;

1/ Without return,

so

the function doesn't

output

the

sum

function

sum(num1, num2)

{

num

num2;

function

add(num1,
num2)

{

return

num

num2;

1/

Defining

the function

function

sum(num1, num2)

{

return

num

num2;

1/ Calling

the function

sum(2,

//

6

Scope

Scope

Scope

is

a concept that refers

to where values and

functions

can

be accessed.

Various

scopes

include:

Global

scope la value/function

in the

global

scope can

be used anywhere

in

the

entire

program)

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)

Block Scoped Variables
Const

and

let

are block scoped variables, meaning

they

are

only accessible

in

their

block

or

nested blocks.

In

the

given code

block, trying

to print the

statusMessage

using

the
console.log()

method

will

result

in

a

ReferenceError.It

is

accessible

only inside that

if

block.

Global Variables

JavaScript variables that

are

declared

outside of blocks

or

functions

can exist in the

global

scope, which

means

they

are

accessible throughout

a program. Variables

declared outside of smaller

block

or

function

scopes are

accessible inside those smaller

scopes.

Note:

It is best practice

to keep

global variables

to

a

minimum.

function

myFunction()

{

var

pizzaName

=

"Volvo";

1/

Code

here

can use
pizzaName
Code

here

can't

use
pizzaName

const

isLoggedIn

=

true;

if

(isLoggedIn

==

true)

{

const statusMessage

=

'User

is

logged in.';

console.log(statusMessage):

Uncaught

ReferenceError:

statusMessage

is

not

defined

Variable declared

globally

const

color

=

'blue':

}

function

printColor()

{

console. log(color);

printColor ():

//

Prints:

blue

Mutable

JavaScript

arrays are

mutable, meaning that the values

they contain

can

be changed.

Even if they

are

declared using Const, the

contents

can

be manipulated

by reassigning

internal

values

or

using methods

like

.push()

and

pop().
Arrays

Arrays

are

lists of ordered, stored data.

They

can

hold

items that

are of

any

data type. Arrays

are

created

by

using

square

brackets,

with individual elements

separated

by

commas.

const

names

=

['Alice', 'Bob'];
names.push('Carl');

1/'Alice'

'Bob', 'Carl']

1/

An array

containing numbers

const numberArray

=

[0, 1, 2, 3];

//

An array

containing

different

data

types

const mixedArray

=

[1,
'chicken',
false];

Loops

Reverse

Loop

A

for

loop

can

iterate "in reverse"

by initializing

the

loop variable to the

starting value, testing for when the

variable hits the ending value, and decrementing

(subtracting from)

the

loop variable at each iteration.

Do...While Statement

A

do.. .while

statement

creates

a

loop

that

exe cutes

a

block of code

once,

checks

if

a

condition

is

true, and then
repeats

the loop

as

long

as

the

condition

is true. They

are

used when

you

want

the

code

to always

execute at least

once.

The loop ends when the condition

evaluates

to false.

const

items

=

['apricot', 'banana',

'cherry']:

for (let

i

=

items. length

i

=

i

{

console.log(

`${i}. ${items

[i]}*):

1/ Prints: 2. cherry

Prints:

1. banana

Prints: 0. apricot

X

=

0

i

=

0

do

{

X

= X +

i;
console.log(x)
i++;

}

while (i

<

1/ Prints:

0 1

3 6 10

Nested

For Loop

A nested

for

loop

is when

a

for

loop

runs

inside

another

for

loop.

The inner loop

will

run all its iterations for

each

iteration

of the

outer loop.

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

as a specified condition evaluates

to

true.

The loop

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

stop.

for

(let

outer

=

0; outer

<

2; outer t=

{

for

(let

inner

=

inner

<

inner

+=

Output:
console.log(`${outer}-${inner}'):

while

(condition)

{

1| code

block

to be

executed

let i

=

while

(i

<

{

console.log(i);
it+;

Iterators

Functions Assigned

to

Variables

In JavaScript, functions

are

a

data

type just

as

strings,

numbers, and

arrays are

data

types. Therefore,

functions

can

be

assigned

as

values

to variables, but

are

different

from

all

other

data types because

they

can

be

invoked.

Callback Functions

In JavaScript,

a

callback function

is

a

function that

is

passed into another function

as an argument. This

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

plusFive

=

(number)

=> {

return

number

1/f is

assigned

the value of

plusFive

let f

=

plusFive;

plusFive(3);

8

Since

f

has
a

function

value,

it

can
be
invoked.
f(9); 1|

14

const isEven

=

(n)

=> {

return

n % 2

==

0;

let

printMsg

=

(evenFunc,
num)

=> {

const isNumEven

=

evenFunc
(num);
console.log(

The

number ${num}

is

an even
number: ${isNumEven}. )
Pass

in isEven

as

the

callback function

printMsg(isEven,

1/ Prints:

The number 4

is

an even
number:

True.