0% found this document useful (0 votes)
9 views71 pages

JavaScript Handout

JavaScript is a dynamic and lightweight programming language that is essential for creating interactive web pages. Initially named LiveScript, it allows client-side scripting and can be executed in browsers and servers. While it offers advantages like reduced server interaction and immediate feedback, it has limitations such as lack of file access and multithreading capabilities.

Uploaded by

aalaa.mady
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views71 pages

JavaScript Handout

JavaScript is a dynamic and lightweight programming language that is essential for creating interactive web pages. Initially named LiveScript, it allows client-side scripting and can be executed in browsers and servers. While it offers advantages like reduced server interaction and immediate feedback, it has limitations such as lack of file access and multithreading capabilities.

Uploaded by

aalaa.mady
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript is the world's most

popular programming language that


is one of the core technologies of
the World Wide Web, alongside
HTML and CSS.
When JavaScript was created, it
initially had another name:
“LiveScript”. But Java was very
popular at that time, so it was
decided that positioning a new
language as a “younger brother” of
Java would help
Its created to “make web pages
alive”. JavaScript can execute not
only in the browser, but also on the
server, or actually on any device
that has a special program called
the JavaScript engine.
JavaScript Introduction
What is JavaScript?
JavaScript is a dynamic computer programming language. It is lightweight and most
commonly used as a part of web pages, whose implementations allow client-side
script to interact with the user and make dynamic pages. It is an interpreted

programming language with object-oriented capabilities.

JavaScript was first known as LiveScript, but Netscape changed its name to

JavaScript, possibly because of the excitement being generated by Java. JavaScript

made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The

general-purpose core of the language has been embedded in Netscape, Internet


Explorer, and other web browsers.

Client-Side JavaScript:
Client-side JavaScript is the most common form of the language. The script should

be included in or referenced by an HTML document for the code to be interpreted by

the browser.
It means that a web page need not be a static HTML, but can include programs that

interact with the user, control the browser, and dynamically create HTML content.

The JavaScript client-side mechanism provides many advantages over traditional CGI
server-side scripts. For example, you might use JavaScript to check if the user has

entered a valid e-mail address in a form field.

Advantages of JavaScript
The merits of using JavaScript are:
• Less server interaction: You can validate user input before sending the page

off to the server. This saves server traffic, which means less load on your

server.
• Immediate feedback to the visitors: They don't have to wait for a page
reload to see if they have forgotten to enter something.

• Increased interactivity: You can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.

• Richer interfaces: You can use JavaScript to include such items as drag-anddrop
components and sliders to give a Rich Interface to your site visitors.

Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the

following important features:

Client-side JavaScript does not allow the reading or writing of files. This has
been kept for security reason.
JavaScript cannot be used for networking applications because there is no such

support available.

JavaScript doesn't have any multithreading or multiprocessor capabilities.

Once again, JavaScript is a lightweight, interpreted programming language that

allows you to build interactivity into otherwise static HTML pages.

JavaScript Development Tools


One of major strengths of JavaScript is that it does not require expensive

development tools. You can start with a simple text editor such as Notepad. Since it

is an interpreted language inside the context of a web browser, you don't even need

to buy a compiler.
JS Where To
the <script> Tag
In HTML, JavaScript code is inserted between <script> and </script> tags.

JavaScript Functions and Events


A JavaScript function is a block of JavaScript code, that can be executed when "called" for.

For example, a function can be called when an event occurs, like when the user clicks a
button.

JavaScript in <head> or <body>


You can place any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML page.

The function is invoked (called) when a button is clicked:


JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML page.

The function is invoked (called) when a button is clicked:

Placing scripts at the bottom of the <body> element improves the display speed, because
script interpretation slows down the display.
External JavaScript
Scripts can also be placed in external files:

External scripts are practical when the same code is used in many different web pages.

JavaScript files have the file extension .js.

To use an external script, put the name of the script file in the src (source) attribute of
a <script> tag:

You can place an external script reference in <head> or <body> as you like.

The script will behave as if it was located exactly where the <script> tag is located.

External scripts cannot contain <script> tags.

External JavaScript Advantages


Placing scripts in external files has some advantages:

• It separates HTML and code


• It makes HTML and JavaScript easier to read and maintain
• Cached JavaScript files can speed up page loads

To add several script files to one page - use several script tags:
External References
An external script can be referenced in 3 different ways:

• With a full URL (a full web address)


• With a file path (like /js/)
• Without any path

This example uses a full URL to link to [Link]:

This example uses a file path to link to [Link]:

This example uses no path to link to [Link]:


JavaScript Output
JavaScript Display Possibilities
JavaScript can "display" data in different ways:

• Writing into an HTML element, using innerHTML.


• Writing into the HTML output using [Link]().
• Writing into an alert box, using [Link]().
• Writing into the browser console, using [Link]().

Using innerHTML
To access an HTML element, JavaScript can use the [Link](id) method.

The id attribute defines the HTML element. The innerHTML property defines the HTML content:

Changing the innerHTML property of an HTML element is a common way to display data in
HTML.

Using [Link]()
For testing purposes, it is convenient to use [Link]():
Using [Link]() after an HTML document is loaded, will delete all existing HTML:

The [Link]() method should only be used for testing.

Using [Link]()
You can use an alert box to display data:
You can skip the window keyword.

In JavaScript, the window object is the global scope object. This means that variables,
properties, and methods by default belong to the window object. This also means that
specifying the window keyword is optional:
Using [Link]()
For debugging purposes, you can call the [Link]() method in the browser to display
data.

You will learn more about debugging in a later chapter.

JavaScript Print
JavaScript does not have any print object or print methods.

You cannot access output devices from JavaScript.

The only exception is that you can call the [Link]() method in the browser to print the
content of the current window.
JavaScript Statements

JavaScript Programs
A computer program is a list of "instructions" to be "executed" by a computer.

In a programming language, these programming instructions are called statements.

A JavaScript program is a list of programming statements.

In HTML, JavaScript programs are executed by the web browser

JavaScript Statements
JavaScript statements are composed of:

Values, Operators, Expressions, Keywords, and Comments.

This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
Most JavaScript programs contain many JavaScript statements.

The statements are executed, one by one, in the same order as they are written.

JavaScript programs (and JavaScript statements) are often called JavaScript code.

Semicolons;
Semicolons separate JavaScript statements.

Add a semicolon at the end of each executable statement:

When separated by semicolons, multiple statements on one line are allowed:

On the web, you might see examples without semicolons.


Ending statements with semicolon is not required, but highly recommended.

JavaScript White Space


JavaScript ignores multiple spaces. You can add white space to your script to make it more
readable.

The following lines are equivalent:

A good practice is to put spaces around operators ( = + - * / ):


JavaScript Line Length and Line Breaks
For best readability, programmers often like to avoid code lines longer than 80 characters.

If a JavaScript statement does not fit on one line, the best place to break it is after an
operator:

JavaScript Code Blocks


JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.

The purpose of code blocks is to define statements to be executed together.

One place you will find statements grouped together in blocks, is in JavaScript functions:
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be
performed.

Our Reserved Words Reference lists all JavaScript keywords.

Here is a list of some of the keywords you will learn about in this tutorial:
JavaScript Syntax

JavaScript Values
The JavaScript syntax defines two types of values:

• Fixed values
• Variable values

Fixed values are called Literals.

Variable values are called Variables.

JavaScript Literals
The two most important syntax rules for fixed values are:

1. Numbers are written with or without decimals:


2. Strings are text, written within double or single quotes:

JavaScript Variables
In a programming language, variables are used to store data values.

JavaScript uses the keywords var, let and const to declare variables.

An equal sign is used to assign values to variables.

In this example, x is defined as a variable. Then, x is assigned (given) the value 6:

JavaScript Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values:

JavaScript uses an assignment operator ( = ) to assign values to variables:

JavaScript Expressions
An expression is a combination of values, variables, and operators, which computes to a
[Link] computation is called an evaluation.

For example, 5 * 10 evaluates to 50:


Expressions can also contain variable values:

The values can be of various types, such as numbers and strings.

For example, "John" + " " + "Doe", evaluates to "John Doe":

JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.

The let keyword tells the browser to create variables:

The var keyword also tells the browser to create variables:

In these examples, using var or let will produce the same result.
JavaScript Comments
Not all JavaScript statements are "executed".

Code after double slashes // or between /* and */ is treated as a comment.

Comments are ignored, and will not be executed:

JavaScript Identifiers / Names


Identifiers are JavaScript names.

Identifiers are used to name variables and keywords, and functions.

The rules for legal names are the same in most programming languages.

A JavaScript name must begin with:

• A letter (A-Z or a-z)


• A dollar sign ($)
• Or an underscore (_)

Subsequent characters may be letters, digits, underscores, or dollar signs.

Note
Numbers are not allowed as the first character in names.

This way JavaScript can easily distinguish identifiers from numbers.

JavaScript is Case Sensitive


All JavaScript identifiers are case sensitive.

The variables lastName and lastname, are two different variables:


JavaScript does not interpret LET or Let as the keyword let.

JavaScript and Camel Case


Historically, programmers have used different ways of joining multiple words into one
variable name:

Hyphens:

first-name, last-name, master-card, inter-city.

Hyphens are not allowed in JavaScript. They are reserved for subtractions.

Underscore:

first_name, last_name, master_card, inter_city.

Upper Camel Case (Pascal Case):

FirstName, LastName, MasterCard, InterCity.

Lower Camel Case:

JavaScript programmers tend to use camel case that starts with a lowercase letter:

firstName, lastName, masterCard, interCity.

JavaScript Character Set


JavaScript uses the Unicode character set.

Unicode covers (almost) all the characters, punctuations, and symbols in the world.
JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to make it more
readable.

JavaScript comments can also be used to prevent execution, when testing alternative
code.

Single Line Comments


Single line comments start with //.

Any text between // and the end of the line will be ignored by JavaScript (will not be
executed).

This example uses a single-line comment before each code line:

This example uses a single line comment at the end of each line to explain the code:

Multi-line Comments
Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored by JavaScript.

This example uses a multi-line comment (a comment block) to explain the code:
Using Comments to Prevent Execution
Using comments to prevent execution of code is suitable for code testing.

Adding // in front of a code line changes the code lines from an executable line to a
comment.

This example uses // to prevent execution of one of the code lines:

This example uses a comment block to prevent execution of multiple lines:


JavaScript Variables
Variables are Containers for Storing Data
JavaScript Variables can be declared in 4 ways:

• Automatically
• Using var
• Using let
• Using const

In this first example, x, y, and z are undeclared variables.

They are automatically declared when first used:

From the examples you can guess:

• x stores the value 5


• y stores the value 6
• z stores the value 11

Note
The var keyword was used in all JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 2015.

The var keyword should only be used in code written for older browsers.
The two variables price1 and price2 are declared with the const keyword.

These are constant values and cannot be changed.

The variable total is declared with the let keyword.

The value total can be changed.

When to Use var, let, or const?


1. Always declare variables

2. Always use const if the value should not be changed

3. Always use const if the type should not be changed (Arrays and Objects)

4. Only use let if you can't use const

5. Only use var if you MUST support old browsers.


Just Like Algebra
Just like in algebra, variables hold values:

variables are used in expressions:

From the example above, you can guess that the total is calculated to be 11.

Note
Variables are containers for storing values.

JavaScript Identifiers
All JavaScript variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

• Names can contain letters, digits, underscores, and dollar signs.


• Names must begin with a letter.
• Names can also begin with $ and _ (but we will not use it in this tutorial).
• Names are case sensitive (y and Y are different variables).
• Reserved words (like JavaScript keywords) cannot be used as names.

The Assignment Operator


In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.

This is different from algebra. The following does not make sense in algebra:
In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.

(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by
5.)

Note
The "equal to" operator is written like == in JavaScript.

JavaScript Data Types


JavaScript variables can hold numbers like 100 and text values like "John Doe".

In programming, text values are called text strings.

JavaScript can handle many types of data, but for now, just think of numbers and strings.

Strings are written inside double or single quotes. Numbers are written without quotes.

If you put a number in quotes, it will be treated as a text string.

Declaring a JavaScript Variable


Creating a variable in JavaScript is called "declaring" a variable.

You declare a JavaScript variable with the var or the let keyword:

After the declaration, the variable has no value (technically it is undefined).


To assign a value to the variable, use the equal sign:

You can also assign a value to the variable when you declare it:

n the example below, we create a variable called carName and assign the value "Volvo" to it.

Then we "output" the value inside an HTML paragraph with id="demo":

One Statement, Many Variables


You can declare many variables in one statement.

Start the statement with let and separate the variables by comma:

A declaration can span multiple lines:


Value = undefined
In computer programs, variables are often declared without a value. The value can be
something that has to be calculated, or something that will be provided later, like user input.

A variable declared without a value will have the value undefined.

The variable carName will have the value undefined after the execution of this statement:

Re-Declaring JavaScript Variables


If you re-declare a JavaScript variable declared with var, it will not lose its value.

The variable carName will still have the value "Volvo" after the execution of these statements:
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators
like = and +:

You can also add strings, but strings will be concatenated:

Note
If you put a number in quotes, the rest of the numbers will be treated as strings, and
concatenated.

JavaScript Dollar Sign $


Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable
names:
Using the dollar sign is not very common in JavaScript, but professional programmers often
use it as an alias for the main function in a JavaScript library.

In the JavaScript library jQuery, for instance, the main function $ is used to select HTML
elements. In jQuery $("p"); means "select all p elements".

JavaScript Underscore (_)


Since JavaScript treats underscore as a letter, identifiers containing _ are valid variable
names:

Using the underscore is not very common in JavaScript, but a convention among
professional programmers is to use it as an alias for "private (hidden)" variables.

JavaScript Let
The let keyword was introduced in ES6 (2015)

Variables defined with let cannot be Redeclared

Variables defined with let must be Declared before use

Variables defined with let have Block Scope


Cannot be Redeclared
Variables defined with let can not be redeclared.

You can not accidentally redeclare a variable declared with let.

Block Scope
Before ES6 (2015), JavaScript had Global Scope and Function Scope.

ES6 introduced two important new JavaScript keywords: let and const.

These two keywords provide Block Scope in JavaScript.

Variables declared inside a { } block cannot be accessed from outside the block:
Variables declared with the var keyword can NOT have block scope.

Variables declared inside a { } block can be accessed from outside the block.

Redeclaring Variables
Redeclaring a variable using the var keyword can impose problems.

Redeclaring a variable inside a block will also redeclare the variable outside the block:

Redeclaring a variable using the let keyword can solve this problem.

Redeclaring a variable inside a block will not redeclare the variable outside the block:
Difference Between var, let and const

What is Good?
let and const have block scope.

let and const can not be redeclared.

let and const must be declared before use.

let and const does not bind to this.

let and const are not hoisted.

What is Not Good?


var does not have to be declared.

var is hoisted.

var binds to this.

Redeclaring
Redeclaring a JavaScript variable with var is allowed anywhere in a program:

With let, redeclaring a variable in the same block is NOT allowed:


Redeclaring a variable with let, in another block, IS allowed:

Let Hoisting
Variables defined with var are hoisted to the top and can be initialized at any time.

Meaning: You can use the variable before it is declared:

If you want to learn more about hoisting, study the chapter JavaScript Hoisting.

Variables defined with let are also hoisted to the top of the block, but not initialized.
Meaning: Using a let variable before it is declared will result in a ReferenceError:

JavaScript Const
The const keyword was introduced in ES6 (2015)

Variables defined with const cannot be Redeclared

Variables defined with const cannot be Reassigned

Variables defined with const have Block Scope

Cannot be Reassigned
A const variable cannot be reassigned:

Must be Assigned
JavaScript const variables must be assigned a value when they are declared:
When to use JavaScript const?
Always declare a variable with const when you know that the value should not be
changed.

Use const when you declare:

• A new Array
• A new Object
• A new Function
• A new RegExp

Constant Objects and Arrays


The keyword const is a little misleading.

It does not define a constant value. It defines a constant reference to a value.

Because of this you can NOT:

• Reassign a constant value


• Reassign a constant array
• Reassign a constant object

But you CAN:

• Change the elements of constant array


• Change the properties of constant object

Constant Arrays
You can change the elements of a constant array:
But you can NOT reassign the array:

But you can NOT reassign the array:

But you can NOT reassign the object:


Difference Between var, let and const

What is Good?
let and const have block scope.

let and const can not be redeclared.

let and const must be declared before use.

let and const does not bind to this.

let and const are not hoisted.

What is Not Good?


var does not have to be declared.

var is hoisted.

var binds to this.

Block Scope
Declaring a variable with const is similar to let when it comes to Block Scope.

The x declared in the block, in this example, is not the same as the x declared outside the
block:

Redeclaring
Redeclaring a JavaScript var variable is allowed anywhere in a program:
Redeclaring an existing var or let variable to const, in the same scope, is not allowed:

Reassigning an existing const variable, in the same scope, is not allowed:

Redeclaring a variable with const, in another scope, or in another block, is allowed:


Hoisting
Variables defined with var are hoisted to the top and can be initialized at any time.

Meaning: You can use the variable before it is declared:

If you want to learn more about hoisting, study the chapter JavaScript Hoisting.

Variables defined with const are also hoisted to the top, but not initialized.

Meaning: Using a const variable before it is declared will result in a ReferenceError:


JavaScript Operators

JavaScript Assignment
The Assignment Operator (=) assigns a value to a variable:

JavaScript Addition
The Addition Operator (+) adds numbers:
JavaScript Multiplication
The Multiplication Operator (*) multiplies numbers:

Types of JavaScript Operators


There are different types of JavaScript operators:

• Arithmetic Operators
• Assignment Operators
• Comparison Operators
• String Operators
• Logical Operators
• Bitwise Operators
• Ternary Operators
• Type Operators

JavaScript Arithmetic Operators


Arithmetic Operators are used to perform arithmetic on numbers:
JavaScript Arithmetic
JavaScript Arithmetic Operators
Arithmetic operators perform arithmetic on numbers (literals or variables).
Arithmetic Operations
A typical arithmetic operation operates on two numbers.

The two numbers can be literals:

or variables:

or expressions:

Operators and Operands


The numbers (in an arithmetic operation) are called operands.

The operation (to be performed between the two operands) is defined by an operator.

Adding
The addition operator (+) adds numbers:
Subtracting
The subtraction operator (-) subtracts numbers.

Multiplying
The multiplication operator (*) multiplies numbers.

Dividing
The division operator (/) divides numbers.
Remainder
The modulus operator (%) returns the division remainder.

In arithmetic, the division of two integers produces a quotient and a remainder.

In mathematics, the result of a modulo operation is the remainder of an arithmetic


division.

Incrementing
The increment operator (++) increments numbers.

Decrementing
The decrement operator (--) decrements numbers.
Exponentiation
The exponentiation operator (**) raises the first operand to the power of the second
operand.

x ** y produces the same result as [Link](x,y):

Operator Precedence
Operator precedence describes the order in which operations are performed in an arithmetic
expression.

Is the result of example above the same as 150 * 3, or is it the same as 100 + 150?

Is the addition or the multiplication done first?

As in traditional school mathematics, the multiplication is done first.

Multiplication (*) and division (/) have higher precedence than addition (+) and subtraction
(-).

And (as in school mathematics) the precedence can be changed by using parentheses.

When using parentheses, the operations inside the parentheses are computed first:
When many operations have the same precedence (like addition and subtraction or
multiplication and division), they are computed from left to right:

JavaScript Assignment
JavaScript Assignment Operators
Assignment operators assign values to JavaScript variables.

Shift Assignment Operators


Bitwise Assignment Operators

Logical Assignment Operators

The = Operator
The Simple Assignment Operator assigns a value to a variable.
The += Operator
The Addition Assignment Operator adds a value to a variable.

The -= Operator
The Subtraction Assignment Operator subtracts a value from a variable.

The *= Operator
The Multiplication Assignment Operator multiplies a variable.

The **= Operator


The Exponentiation Assignment Operator raises a variable to the power of the operand.
The /= Operator
The Division Assignment Operator divides a variable.

The %= Operator
The Remainder Assignment Operator assigns a remainder to a variable.

The <<= Operator


The Left Shift Assignment Operator left shifts a variable.

The >>= Operator


The Right Shift Assignment Operator right shifts a variable (signed).
The >>>= Operator
The Unsigned Right Shift Assignment Operator right shifts a variable (unsigned).

The &= Operator


The Bitwise AND Assignment Operator does a bitwise AND operation on two operands
and assigns the result to the the variable.

The |= Operator
The Bitwise OR Assignment Operator does a bitwise OR operation on two operands and
assigns the result to the variable.

The ^= Operator
The Bitwise XOR Assignment Operator does a bitwise XOR operation on two operands
and assigns the result to the variable.
The &&= Operator
The Logical AND assignment operator is used between two values.

If the first value is true, the second value is assigned.

The ||= Operator


The Logical OR assignment operator is used between two values.

If the first value is false, the second value is assigned.

The ??= Operator


The Nullish coalescing assignment operator is used between two values.

If the first value is undefined or null, the second value is assigned.


JavaScript Assignment
JavaScript Assignment Operators
Assignment operators assign values to JavaScript variables.

Shift Assignment Operators

Bitwise Assignment Operators


Logical Assignment Operators

The = Operator
The Simple Assignment Operator assigns a value to a variable.

The += Operator
The Addition Assignment Operator adds a value to a variable.
The -= Operator
The Subtraction Assignment Operator subtracts a value from a variable.

The *= Operator
The Multiplication Assignment Operator multiplies a variable.

The **= Operator


The Exponentiation Assignment Operator raises a variable to the power of the operand.

The /= Operator
The Division Assignment Operator divides a variable.
The %= Operator
The Remainder Assignment Operator assigns a remainder to a variable.

The <<= Operator


The Left Shift Assignment Operator left shifts a variable.

The >>= Operator


The Right Shift Assignment Operator right shifts a variable (signed).

The >>>= Operator


The Unsigned Right Shift Assignment Operator right shifts a variable (unsigned).
The &= Operator
The Bitwise AND Assignment Operator does a bitwise AND operation on two operands
and assigns the result to the the variable.

The |= Operator
The Bitwise OR Assignment Operator does a bitwise OR operation on two operands and
assigns the result to the variable.

The ^= Operator
The Bitwise XOR Assignment Operator does a bitwise XOR operation on two operands
and assigns the result to the variable.

The &&= Operator


The Logical AND assignment operator is used between two values.

If the first value is true, the second value is assigned.


The ||= Operator
The Logical OR assignment operator is used between two values.

If the first value is false, the second value is assigned.

The ??= Operator


The Nullish coalescing assignment operator is used between two values.

If the first value is undefined or null, the second value is assigned.


JavaScript Data Types
The Concept of Data Types
In programming, data types is an important concept.

To be able to operate on variables, it is important to know something about the type.

Without data types, a computer cannot safely solve this:

Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it produce
a result?

JavaScript will treat the example above as:

JavaScript evaluates expressions from left to right. Different sequences can produce
different results:
In the first example, JavaScript treats 16 and 4 as numbers, until it reaches "Volvo".

In the second example, since the first operand is a string, all operands are treated as
strings.

JavaScript Types are Dynamic


JavaScript has dynamic types. This means that the same variable can be used to hold
different data types:

JavaScript Strings
A string (or a text string) is a series of characters like "John Doe".

Strings are written with quotes. You can use single or double quotes:
You can use quotes inside a string, as long as they don't match the quotes surrounding the
string:

JavaScript Numbers
All JavaScript numbers are stored as decimal numbers (floating point).

Numbers can be written with, or without decimals:

Exponential Notation
Extra large or extra small numbers can be written with scientific (exponential) notation:
Note
Most programming languages have many number types:

Whole numbers (integers):


byte (8-bit), short (16-bit), int (32-bit), long (64-bit)

Real numbers (floating-point):


float (32-bit), double (64-bit).

Javascript numbers are always one type:


double (64-bit floating point).

JavaScript BigInt
All JavaScript numbers are stored in a a 64-bit floating-point format.

JavaScript BigInt is a new datatype (ES2020) that can be used to store integer values that
are too big to be represented by a normal JavaScript Number.

JavaScript Booleans
Booleans can only have two values: true or false.

Booleans are often used in conditional testing.


JavaScript Arrays
JavaScript arrays are written with square brackets.

Array items are separated by commas.

The following code declares (creates) an array called cars, containing three items (car
names):

Array indexes are zero-based, which means the first item is [0], second is [1], and so on.

JavaScript Objects
JavaScript objects are written with curly braces {}.

Object properties are written as name:value pairs, separated by commas.

The object (person) in the example above has 4 properties: firstName, lastName, age, and
eyeColor.

The typeof Operator


You can use the JavaScript typeof operator to find the type of a JavaScript variable.

The typeof operator returns the type of a variable or an expression:


Undefined
In JavaScript, a variable without a value, has the value undefined. The type is also undefined.

Empty Values
An empty value has nothing to do with undefined.

An empty string has both a legal value and a type.


JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).

JavaScript Function Syntax


A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}


Function parameters are listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.

Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:

• When an event occurs (when a user clicks a button)


• When it is invoked (called) from JavaScript code
• Automatically (self invoked)

You will learn a lot more about function invocation later in this tutorial.

Function Return
When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute the code
after the invoking statement.

Functions often compute a return value. The return value is "returned" back to the "caller":

Why Functions?
With functions you can reuse code

You can write code that can be used many times.

You can use the same code with different arguments, to produce different results.
The () Operator
The () operator invokes (calls) the function:

Accessing a function with incorrect parameters can return an incorrect answer:

Accessing a function without () returns the function and not the function result:

Functions Used as Variable Values


Functions can be used the same way as you use variables, in all types of formulas,
assignments, and calculations.
Local Variables
Variables declared within a JavaScript function, become LOCAL to the function.

Local variables can only be accessed from within the function.

Since local variables are only recognized inside their functions, variables with the same
name can be used in different functions.

Local variables are created when a function starts, and deleted when the function is
completed.

You might also like