Online Digital Class-Node.
js
Programming for Maker
Lesson 2
Time: 16 May 2020 (09:00 AM – 11:00 AM)
By ICTSIG@IEM
Outline
• JavaScript Functions.
• JavaScript Objects
JavaScript Functions
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).
• A JavaScript function is defined with the function keyword, followed
by a name, followed by parentheses ().
JavaScript Functions
• 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: {}
JavaScript Functions
• function name(parameter1, parameter2, parameter3) {
// code to be executed
}
• 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":
Example
• Calculate the product of two numbers, and return the result:
• function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
• var x = myFunction(4, 3); // Function is called, return value will end up in x
• console.info(x);
• Var y = myFunction(2, 5);
• console.info(y);
Why Functions?
• You can reuse code: Define the code once, and use it many
times.
• You can use the same code many times with different
arguments, to produce different results.
The () Operator Invokes the Function
• Using the example above, toCelsius refers to the function
object, and toCelsius() refers to the function result.
• Accessing a function without () will return the function
object instead of the function result.
Example
function greet(){
console.info(“Hello World”);
}
• greet();
Exercise
• function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
console.info(toCelsius(77));
• console.info(toCelsius(87));
• var temperature=52;
• console.info(toCelsius(temperature));
• toCelsius
• typeof(toCelsius)
Exercise
• function toCelsius(fahrenheit,constant) {
return (5/9) * (fahrenheit-Constant);
}
• console.info(toCelsius(12,32));
• console.info(toCelsius(32,32));
Functions Used as Variable Values
• Functions can be used the same way as you use variables, in
all types of formulas, assignments, and calculations.
Exercise
• var x = toCelsius(77);
var text = "The temperature is " + x + " Celsius";
• console.info(text);
• var text = "The temperature is " + toCelsius(77) + " Celsius";
• console.info(text);
Local Variables
• Variables declared within a JavaScript function, become LOCAL to the
function.
• Local variables can only be accessed from within the function.
Exercise
• // code here can NOT use carName
var carName=“Proton”;
• console.info(carName);
• console.info(myFunction());
function myFunction() {
var carName = "Volvo";
// code here CAN use carName
• console.info(carName);
}
// code here can NOT use carName
• var carName=“ABC”;
• console.info(carName);
Local Variable
• 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.
JavaScript Objects
Real Life Objects, Properties, and Methods
• In real life, a car is an object.
• A car has properties like weight and color, and methods like start and
stop:
Object Properties
• All cars have the same properties, but the property values differ from
car to car.
• All cars have the same methods, but the methods are performed at
different times.
JavaScript Objects
• You have already learned that JavaScript variables are containers for
data values.
• This code assigns a simple value (Fiat) to a variable named car:
• var car = "Fiat";
• console.info(car);
JavaScript Objects
• Objects are variables too. But objects can contain many values.
• This code assigns many values (Fiat, 500, white) to a variable named
car:
• // Create an object:
• var car = {type:"Fiat", model:"500", color:"white"};
• // Display some data from the object:
• console.info("The car type is " + car.type);
Object Definition
• You define (and create) a JavaScript object with an object literal:
• var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
• // Display some data from the object:
• console.log(person.firstName + " is " + person.age + " years old.“);
Object Properties
• The name: values pairs in JavaScript objects are called properties:
• Property: Property Value
• firstName: John
• lastName: Doe
• Age: 50
• eyeColor: blue
Accessing Object Properties
• You can access object properties in two ways:
• objectName.propertyName
• or
• objectName["propertyName"]
• Example1
• person.lastName;
Exercise
• // Create an object:
• var person = {
• firstName: "John",
• lastName : "Doe",
• id : 5566
• };
• // Display some data from the object:
• console.log(person.firstName + " " + person.lastName);
Exercise
• Spaces and line breaks are not important. An object definition can span multiple lines:
• // Create an object:
• var person = {
• firstName: "John",
• lastName: "Doe",
• age: 50,
• eyeColor: "blue"
• };
• // Display some data from the object:
• console.info(person.firstName + " is " + person.age + " years old.“);
Object Methods
• Objects can also have methods.
• Methods are actions that can be performed on objects.
• Methods are stored in properties as function definitions.
Property Property Value
firstName John
lastName Doe
age 50
eyeColor blue
fullName function() {return this.firstName + " " + this.lastName;}
The this Keyword
• In a function definition, this refers to the "owner" of the function.
• In the example above, this is the person object that "owns" the
fullName function.
• In other words, this.firstName means the firstName property of this
object.
• Read more about the this keyword at JS this Keyword.
Accessing Object Methods
• You access an object method with the following syntax:
• objectName.methodName()
Exercise
• var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
• console.log( person.fullName());
Do Not Declare Strings, Numbers, and Booleans as
Objects!
• When a JavaScript variable is declared with the keyword "new", the
variable is created as an object:
• var x = new String(); // Declares x as a String object
• var y = new Number(); // Declares y as a Number object
• var z = new Boolean(); // Declares z as a Boolean object
• Avoid String, Number, and Boolean objects. They complicate your
code and slow down execution speed.
Homework 1
• Execute the function named myFunction.
• Then allow pass in external message as argument to the parameter of
the function
function myFunction() {
console.log("Hello World!");
}
Homework 2
• If John is the IEM member, introduce the properties of his
membership id, discipline. Construct a method to display the
membership id and name by extracting information from the member
object.
• var member = {
• firstName: "John",
• lastName: "Doe“
• showInfo:
• };
Homework 3
• Based on Homework 2, construct methods to allow to assign
property’s values;
Thank you
Q&A