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

Understanding JavaScript Data Types

Uploaded by

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

Understanding JavaScript Data Types

Uploaded by

Karthik S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Understanding

JavaScript
Defining Variables

 Variables are a means to name data so that you can use that name to
temporarily store and access data from your JavaScript files.

 Variables can point to simple data types such as numbers or strings, or they can
point to more complex data types such as objects.

 To define a variable in JavaScript you use the var keyword and then give the
variable a name,

 For example:

var myData;
Defining Variables

 We can also assign a value to the variable in the same line.

 For example, the following line of code creates a variable myString and assigns
it the value of "Some Text":

var myString = "Some Text";

 The following lines work as well:

var myString;

myString = "Some Text";


Defining Variables

 Once you have declared the variable, you can use the name to assign the
variable a value and access the value of the variable.

 For example, the following code stores a string into the myString variable and
then uses it when assigning the value to the newString variable:

var myString = "Some Text";

var newString = myString + " Some More Text";

 The only rules for creating variable names is that they must begin with a letter,
$, or _, and they cannot contain spaces.

 Variable names are case sensitive, so using myString is different from MyString.
Understanding JavaScript Data Types

 JavaScript uses data types to determine how to handle data assigned to a


variable.

 The variable type determines what operations you can perform on the variable.

 Common data types are:

 String: Stores character data as a string. The character data is specified by


either single or double quotes.

 For example:

var myString = 'Some Text’;

var anotherString = 'Some More Text';


Understanding JavaScript Data Types
 Number: Stores the data as a numerical value. Numbers are useful in counting,
calculations, and comparisons.

 For example:

var myInteger = 1;

var cost = 1.33;

 Boolean: Stores a single bit that is either true or false. Booleans are often used
for flags.

 For example:

var yes = true;

var no = false;
Understanding JavaScript Data Types
 Array: An indexed array is a series of separate distinct data items all stored
under a single variable name.

 Items in the array can be accessed by their zero-based index using array[index].

 The following example creates a simple array and then accesses the first
element, which is at index 0.

var arr = ["one", "two", "three"]

var first = arr[0];

 Null: At times you do not have a value to store in a variable either because it
hasn’t been created or you are no longer using it.

 At that time you can set a variable to null.

var newVar = null;


Understanding JavaScript Data Types

 Object literal: JavaScript supports the ability to create and use object literals.

 When you use an object literal you can access values and functions in the object
using the object.property syntax.

 The following example shows how to create and access properties of an object
literal:

var obj = {"name": "Brendan", "Hobbies":["Video Games", "camping"],


"age“:

"Unknown"};

var name = obj.name;


Creating Functions

 One of the most important parts of JavaScript is making code that is reusable by
other code.

 To do this you organize your code into functions that perform specific tasks.

 A function is a series of code statements combined together in a single block


and given a name.

 The code in the block can then be executed by referencing that name.
Creating Functions
 Defining Functions

 Functions are defined using the function keyword followed by a name that
describes the use of the function, a list of zero or more arguments in (), and a
block of one or more code statements in {}.

 For example, the following is a function definition that writes "Hello World" to the
console.

function myFunction(){

console.log("Hello World");

 To execute the code in myFunction(), add the following line to the main JavaScript
or inside another function.

myFunction();
Creating Functions
 Passing Variables to Functions

 Frequently you need to pass specific values to functions.

 Values are passed in comma-delimited form to the function.

 The function definition needs a list of variable names in () that match the
number being passed in.

 For example, the following function accepts two arguments, a name and city,
and uses them to build the output string:

function greeting(name, city){

console.log("Hello " + name);

console.log(". How is the weather in " + city);

}
Creating Functions

 To call the greeting() function, you need to pass in a name value and a city
value.

 The value can be a direct value or a previously defined variable.

 To illustrate this, the following code executes the greeting() function with a
name variable and a direct string for the city:

var name = "Brad";

greeting(name, "Florence");
Creating Functions
 Returning Values from Functions

 Functions need to return a value to the calling code.

 Adding a return keyword followed by a variable or value returns that value from the
function.

 For example, the following code calls a function to format a string, assigns the value
returned from the function to a variable, and then writes the value to the console:

function formatGreeting(name, city){

var retStr = "";

retStr += "Hello <b>" + name +"<b>,<br>);

retStr += "Welcome to " + city + "!";

return retStr;

}
Creating Functions
var greeting = formatGreeting("Brad", "Rome");

console.log(greeting);

 You can include more than one return statement in the function.

 When the function encounters a return statement, code execution of the function
is stopped immediately.

 If the return statement contains a value to return, then that value is returned.

function myFunc(value){

if (value == 0)

return value;

<code_to_execute_if_value_nonzero>

return value;

}
Creating Functions
 Using Anonymous Functions

 JavaScript also provides the ability to create anonymous functions.

 Anonymous functions can be used as parameters to functions, properties of an


object, or to return values from a function.

 These functions have the advantage of being defined directly in the parameter
sets when calling other functions.

 You do not need a formal definition.

 For example, the following code defines a function, doCalc(), that accepts three
parameters.

 The first two should be numbers, and the third is a function that will be called
and pass the two numbers as arguments:
Creating Functions

function doCalc(num1, num2, calcFunction){

return calcFunction(num1, num2);

 You could define a function and then pass the function name without parameters to
doCalc().

 For example:

function addFunc(n1, n2){

return n1 + n2;

doCalc(5, 10, addFunc);


Creating Functions

 You also have the option to use an anonymous function directly in the call to
doCalc(), as shown in the following two statements:

console.log( doCalc(5, 10, function(n1, n2){ return n1 + n2; }) );

console.log( doCalc(5, 10, function(n1, n2){ return n1 * n2; }) );

 The advantage of using anonymous functions is that you do not need a formal
definition because it will not be used anywhere else in your code.

 This makes JavaScript code more concise and readable.


Understanding Variable Scope

 Variable scope is simply “the value of a specific variable name at the current
line of code being executed.”

 JavaScript allows you to define both a global and a local version of the variable.

 The global version is defined in the main JavaScript, and local versions are
defined inside functions.

 When you define a local version in a function, a new variable is created in


memory.

 Within that function you reference the local version.

 Outside that function, you reference the global version.


Understanding Variable Scope
 To understand variable scoping better, consider the following code:

var myVar = 1;

function writeIt(){

var myVar = 2;

console.log("Variable = " + myVar);

writeMore();

function writeMore(){

console.log("Variable = " + myVar);

writeIt();
Understanding Variable Scope

 The global variable myVar is defined on line 1; then on line 3 a local version is
defined within the writeIt() function.

 Line 4 writes "Variable = 2" to the console.

 Then in line 5, writeMore() is called.

 Since no local version of myVar is defined in writeMore(), the value of the global
myVar is written in line 8.
Using JavaScript Objects

 JavaScript has several built-in objects such as Number, Array, String, Date, and
Math.

 Each of these built-in objects has member properties and methods.

 In addition to the JavaScript objects, Node.js, MongoDB, Express, and Angular


add their own built-in objects as well.

 JavaScript provides a nice object-oriented programming structure for you to


create your own custom objects.

 Using objects rather than just a collection of functions is key to writing clean,
efficient, reusable JavaScript code.
Using JavaScript Objects

 Using Object Syntax

 To use objects in JavaScript effectively, you need to have an understanding of


their structure and syntax.

 An object is really just a container to group multiple values and, in some


instances, functions together.

 The values of an object are called properties, and functions are called methods.

 To use a JavaScript object, you must first create an instance of the object.

 Object instances are created using the new keyword with the object constructor
name.
Using JavaScript Objects

 For example, to create a number object, you use the following line of code to
create an instance of the built-in Number object in JavaScript:

var x = new Number ("5");

 Object syntax is straightforward: You use the object name, followed by a dot,
and then the property or method name.

 For example, the following lines of code get and set the name property of an
object named myObj:

var s = myObj.name;

myObj.name = "New Name";


Using JavaScript Objects

 You can also get and set object methods of an object in the same manner.

 For example, the following lines of code call the getName() method and then
change the method function on an object named myObj:

var name = myObj.getName();

myObj.getName = function() { return this.name; };

 You can also create objects and assign variables and functions directly using {}
syntax.
Using JavaScript Objects

 For example, the following code defines a new object and assigns values and a
method function.

 You can also get and set object methods of an object in the same manner.

var obj = {

name: "My Object",

value: 7,

getValue: function() { return this.value; }

};
Using JavaScript Objects

 You can also access members of a JavaScript object using the


object[propertyName] syntax.

 This is useful when you are using dynamic property names or if the property
name must include characters not supported by JavaScript.

 The following examples access the "User Name" and "Other Name" properties of
an object named myObj:

var propName = "User Name";

var val1 = myObj[propName];

var val2 = myObj["Other Name"];


Using JavaScript Objects
 Creating Custom-Defined Objects

 JavaScript objects can be defined in a couple different ways.

 The simplest way is the on-the-fly method: You create a generic object and then
add properties to it as needed.

 For example, to create a user object and assign a first and last name as well as
define a function to return the name, you could use the following code:

var user = new Object();

user.first="Brendan";

user.last="Dayley";

user.getName = function() { return this.first + " " + this.last; }


Using JavaScript Objects
 You could also accomplish the same thing through direct assignment using the
following syntax where the object is enclosed in {} and the properties are
defined using property:value syntax:

var user = {

first: Brendan,

last: 'Dayley',

getName: function() { return this.first + " " + this.last; }};

 These first two options work well for simple objects that you do not need to
reuse later.

 A better method for reusable objects is to actually enclose the object inside its
own function block. This has the advantage of allowing you to keep all the code
pertaining to the object local to the object itself.
Using JavaScript Objects

 For example:

function User(first, last){

this.first = first;

this.last = last;

this.getName = function( ) { return this.first + " " + this.last; }};

var user = new User("Brendan", "Dayley");

 The end result of these methods is essentially the same: You have an object
with properties that that can be referenced using dot syntax as shown here:

console.log(user.getName());
Using JavaScript Objects

 Using a Prototyping Object Pattern

 An even more advanced method of creating objects is using a prototyping


pattern.

 The prototyping pattern is implemented by defining the functions inside the


prototype attribute of the object instead of the object itself.

 The advantage of prototyping is that the functions defined in the prototype are
created only once when the JavaScript is loaded, instead of each time a new
object is created.
Using JavaScript Objects
 For example,

function UserP(first, last){

this.first = first;

this.last = last;

UserP.prototype = {

getFullName: function(){

return this.first + " " + this.last;

};
Using JavaScript Objects

 The above example shows the code necessary to implement the prototyping
pattern.

 Notice that the object UserP is defined and then the UserP.prototype is set to
include the getFullName() function.

 You can include as many functions in the prototype as you want.

 Each time a new object is created, those functions will be available.


Manipulating Strings

 The String object is by far the most commonly used object in JavaScript.

 JavaScript automatically creates a String object for you any time you define a
variable that has a string data type.

 For example:

var myStr = "Teach Yourself jQuery & JavaScript in 24 Hours";

 When creating a string, several special characters cannot be directly added to


the string.

 For these characters, JavaScript provides a set of escape codes.


Manipulating Strings
Manipulating Strings
 To determine the length of the string, you can use the length property of the
String object.

 For example:

var numOfChars = myStr.length;

 The String object has several functions that allow you to access and manipulate
the string in various ways.

 The methods for string manipulation are given below.


Manipulating Strings
Manipulating Strings
Manipulating Strings
 Combining Strings

 Multiple strings can be combined either by using a + operation or by using the


concat() function on the first string.

 For example, in the following code sentence1 and sentence2 will be the same:

var word1 = "Today ";

var word2 = "is ";

var word3 = "tomorrow\'s";

var word4 = "yesterday.";

var sentence1 = word1 + word2 + word3 + word4;

var sentence2 = word1.concat(word2, word3, word4);


Manipulating Strings

 Searching a String for a Substring

 To tell whether a string is a substring of another, you can use the indexOf()
method.

 For example, the following code writes the string to the console only if it
contains the word “think”:

var myStr = "I think, therefore I am.";

if (myStr.indexOf("think") != -1){

console.log (myStr);

}
Manipulating Strings

 Replacing a Word in a String

 Another common String object task is replacing one substring with another.

 To replace a word or phrase in a string, use the replace() method.

 The following code replaces the text "<username>" with the value of the
variable username:

var username = "Brendan";

var output = "<username> please enter your password: ";

output.replace("<username>", username);
Manipulating Strings

 Splitting a String into an Array

 A common task with strings is to split them into arrays using a separator character.

 For example, the following code splits a time string into an array of its basic parts
using the split() method on the ":" separator:

var t = "12:10:36";

var tArr = t.split(":");

var hour = t[0];

var minute = t[1];

var second = t[2];

You might also like