0% found this document useful (0 votes)
2 views15 pages

Week 3 Class Note

This document covers JavaScript fundamentals, focusing on objects, loops, and functions. It explains the nature of JavaScript objects, the concept of primitive values, and various methods for creating and manipulating objects. Additionally, it details different types of loops and the importance of functions in programming, including their structure, usage, and the concept of hoisting.

Uploaded by

ettolrahcava
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views15 pages

Week 3 Class Note

This document covers JavaScript fundamentals, focusing on objects, loops, and functions. It explains the nature of JavaScript objects, the concept of primitive values, and various methods for creating and manipulating objects. Additionally, it details different types of loops and the importance of functions in programming, including their structure, usage, and the concept of hoisting.

Uploaded by

ettolrahcava
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

JavaScript Fundamentals

WEEK 03
INSTRUCTORS:
OFURUM CHIZITERE || chizzy.o@deebug.org
OGHAMOMWAN SAMUEL || samuel@deebug.org
Objects, Loops, Functions

JavaScript Objects

JavaScript is all about objects, a large part of what makes JavaScript so dynamic are objects.
If you understand objects, you pretty much understand JavaScript.
In JavaScript, almost "everything" is an object.

● Booleans can be objects (if defined with the new keyword)


● Numbers can be objects (if defined with the new keyword)
● Strings can be objects (if defined with the new keyword)
● Dates are always objects
● Maths are always objects
● Regular expressions are always objects
● Arrays are always objects
● Functions are always objects
● Objects are always objects
● All JavaScript values, except primitives, are objects.

A brief on JavaScript Primitives


A primitive value is a value that has no properties or methods.
A primitive data type is data that has a primitive value.
JavaScript defines 5 types of primitive data types:
● string
● number
● boolean
● null
● undefined
Primitive values are immutable (they are hardcoded and therefore cannot be changed).

Objects are special variables


Objects are variables too. But objects can contain many values.
Object values are written as name : value pairs (name and value separated by a colon).

Object Properties
A JavaScript object is a collection of named values.
The named values, in JavaScript objects, are called properties.
The properties in the above object are;
firstName, lastName, age, eyeColor.

Accessing the data in an object through it’s properties


Properties are the values associated with a JavaScript object.
A JavaScript object is a collection of unordered properties.
Properties can usually be changed, added, and deleted, but some are read only.

The syntax for accessing the property of an object is:

The expression must evaluate to a property name.

Creating a JavaScript Object


With JavaScript, you can define and create your own objects.
There are different ways to create new objects:

● Create a single object, using an object literal.


● Create a single object, with the keyword new.
● Define an object constructor, and then create objects of the constructed type.
● Create an object using Object.create().

Create a single object, using an object literal.


This is the easiest way to create a JavaScript Object.
Using an object literal, you both define and create an object in one statement.
An object literal is a list of name:value pairs (like age:100) inside curly braces {}.
The following example creates a new JavaScript object with four properties:
Spaces and line breaks are not important. An object definition can span multiple lines:
Object Literals

Using the JavaScript Keyword new


The following example create a new JavaScript object using new Object(), and then adds 4
properties:

Creating Objects
This example creates an empty JavaScript object, and then adds 4 properties:
JavaScript Objects are Mutable
Objects are mutable: They are addressed by reference, not by value.
If person is an object, the following statement will not create a copy of person:

The object x is not a copy of person. It is person. Both x and person are the same object.
Any changes to x will also change person, because x and person are the same object.

Arrays vs Objects
In JavaScript, arrays use numbered indexes.
In JavaScript, objects use named indexes

When to Use Arrays vs When to use Objects.


You should use objects when you want the element names to be strings (text).
You should use arrays when you want the element names to be numbers.
JavaScript Loops

Loops can execute a block of code as long as a specified condition is true.


Loops are an integral part of software development, if you want to run the same code over
and over again, each time with a different value, a loop will get the job done.
this is often the case when working with arrays:
JavaScript supports different kinds of loops:
● for - loops through a block of code a number of times
● for/in - loops through the properties of an object
● for/of - loops through the values of an iterable object
● while - loops through a block of code while a specified condition is true
● do/while - also loops through a block of code while a specified condition is true

Example
In the following example, the code in the loop will run, over and over again, as long as a
variable (i) is less than 10:

While Loop
The while loop loops through a block of code as long as a specified condition is true.

Note: If you forget to increase the variable used in the condition, the loop will never end.
This will crash your browser.
The Do While Loop
The do while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition
is true.

The example below uses a do while loop. The loop will always be executed at least once,
even if the condition is false, because the code block is executed before the condition is
tested:

The For Loop


The for loop has the following syntax:

Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
The For in Loop
The JavaScript for in statement loops through the properties of an Object:

For In Over Arrays


The JavaScript for in statement can also loop over the properties of an Array:

Do not use for in over an Array if the index order is important.


The index order is implementation-dependent, and array values may not be accessed in
the order you expect.
It is better to use a for loop, a for of loop, or Array.forEach() when the order is important.

Array.forEach()
The forEach() method calls a function (a callback function) once for each array element.
Note that the function takes 3 arguments:
The item value
The item index
The array itself
The example above uses only the value parameter. It can be rewritten to:

The For Of Loop


The JavaScript for of statement loops through the values of an iterable object.
It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and
more:

variable - For every iteration the value of the next property is assigned to the variable.
Variable can be declared with const, let, or var.
iterable - An object that has iterable properties.
Browser Support
For/of was added to JavaScript in 2015 (ES6)

Looping over an Array

Looping over a String

JavaScript Functions

Functions/Methods are “self contained” modules/blocks of code that accomplish a specific


task. Most functions “take in” some data, process it, and “return” a result. This data the
function takes in, is usually in the form of variables or literal values.

The process of creating a function is called a “function definition” or “function


declaration”, and once a function has been defined, it can be used as many times as you
need it almost anywhere in your program. The process of using a function is called a
“function call”. Functions can also be “called” from the inside of other functions.
Every modern programming language and most of the languages of the past which are still
being used in this present time allow you to create functions. Functions basically
“Encapsulate” the execution of a task which would normally span several lines of code and
basically combine them into one line of code.

Most programming languages provide built in functions; these are functions which have
already been defined by the creators of the programming language to carry out specific
tasks. These functions usually carry out commonly needed operations, which would
normally require several steps/lines of code to accomplish. It is good practice to have a
good knowledge of as many of the built in functions as possible available to you in
JavaScript. This will invariably save you a lot of time.

For instance, computing the square root of a number. In general, we as programmers don’t
really care about how the function for finding the square root of a number does what it
does, only that it “does it”.

Function control flow


When a function gets “called”, the program “leaves” (moves) from the current section/block
of code and begins to execute the first line of code within the function which was called.

Function flow control is thus:


● The program gets to a line of code which contains a function call
● The program enters the function and starts executing the first line of code within
the function
● All instructions/lines of code inside the function are executed from top to bottom
● The program then leaves the function and goes back to where it started from (the
line of code and position where the function was initially called).
● Any data computed and returned by the function is used in place of the function in
the original line of code.

Importance of writing a function


Functions allow you as a programmer to conceive of your programs as a bunch of
sub-steps instead of a complex whole. Each sub-step can therefore be its own function.
Always remember, when a program starts looking too complex, break the entire program
into sub-steps.

One of the best things about functions is that they allow you as a programmer to reuse
code, instead of rewriting it from scratch.

Another great thing about functions is that functions allow us to keep our variable
namespace clean. What this means is that local variables only “live” as long as the function
does. Therefore, function_a can have and use a variable called I, and function_b can also
use a variable called I and there will be no confusion because each variable I only exists
when the computer is in the process of executing that specific function.

Functions also allow us to do isolated testing of certain aspects of our program.

Necessary steps to take before defining a function


Understand the purpose of the function you are about to define

Carefully define the data which might need to come into the function from the caller in the
form of parameters.

Also carefully define what data variables might be needed within the function to
accomplish its task.

Decide on the set of steps

Following our black box example in the beginning of this course, functions can be called
black boxes because we don’t necessarily need to know how they work, just what is
supposed to go into them to enable them carry out their operations successfully, and what
is supposed to come out of them.

Parts of a function
When defining a function, we must spell out the following attributes of the function;
The Name: This describes the purpose of the function. Usually some sort of verb or
phrase, such as “signUp”, or “play”.
The Inputs: called parameters. These describe what data is needed by the function for it to
work.
The calculation/statements: This varies for each function.
The output: Value/values that are computed inside the function and “returned”.

Function Workspace
Every function has its own Workspace. This means that every variable inside the function is
only usable during the execution of the function (and then the variables go away).
Having a separate "workspace" for each function is critical to proper software engineering.
If every function shared every variable in an entire program, it would be easy to
inadvertently change the values of variables that you shouldn't. Further, it would be hard to
remember what "names" have been used elsewhere, and coming up with new names to
represent similar ideas would be challenging.
A side-effect of function variables not existing after the end of the function is that the only
way to get information "out" of a function is by "returning" that information via the output
of the function.

Additionally, the function can only "see" the information that is "passed" to it via
parameters. Thus the only way information can get "in" to the function is by using
parameters.

Note: In certain object oriented languages (e.g., C++, Java, ActionScript), a function can also
see all of the variables associated with its containing object.

Function syntax
Function Example

Semicolons are used to separate executable JavaScript statements.


Since a function declaration is not an executable statement, it is not common to end it with
a semicolon.
Function Expressions
A JavaScript function can also be defined using an expression.
A function expression can be stored in a variable:

After a function expression has been stored in a variable, the variable can be used as a
function:

The function above is actually an anonymous function (a function without a name).


Functions stored in variables do not need function names. They are always invoked (called)
using the variable name.
The function above ends with a semicolon because it is a part of an executable statement.

Function Hoisting
Hoisting is JavaScript's default behavior of moving declarations/definitions to the top of the
current scope.
Hoisting applies to function declarations/definitions.
Because of this, JavaScript functions can be called before they are declared:

You might also like