Você está na página 1de 71

Variables

Learning Goals
Understand the purpose of variables
Declare and assign value to variables
Understand the JavaScript variables types
Use variables in your scripts

What is a Variable?
A variable represents or holds a value
In other words, its a container
Actual can be changed at any time

What is a Variable?
Variables in JavaScript similar to those in
mathematics
Give variable a name, assign values
If value of variable changes, something
will happen within the script

Example of a Variable

x=2

Example of a Variable
x is name of variable
Assigned a value of 2
To change value of variable, give x new
assignment

Example of a Variable

x=4

Example of a Variable
Name of variable remains same, but
represents different value

Why are Variables Useful?


Save time in writing and updating code
Make purpose of code clearer

Variables as Time Savers


Speeds up because values of variables
can change
Assign value to variable at the beginning
of script
Rest of script uses variable

Variables as Time Savers


If value of variable changes, only need to
change code in one place

Variables as Time Savers


If x = 2, then
3+x1+2x=?
3+x1+2x=4

Variables as Time Savers


Do not need to re-write problem for a
different value of x
Simply change value of x
Variables very useful in long and complex
problems

Variables as Code Clarifiers


Variables easier to recognize in code
Why?
Represent something
Have meaningful names

Variables as Code Clarifiers


TotalPrice = 48.57 + 27.50;
TotalPrice = Petrol + CNG;

Variables as Code Clarifiers


Do not need to remember meaning of
numbers
Meaningful variable names make it easier
to spot errors

Defining Variables
Declaring variables
Assigning values to variables
Naming variables

Declaring Variables
Create variables by declaring them
Use var keyword to declare text as
variable
Var keyword tells browser that text to
follow is name of new variable

Declaring Variables

var variablename;

Declaring Variables
var car;
var height;
var name, address, phoneNumber;

Assigning Values to Variables


Variables can be assigned a value:
When declaring a variable
Later on

Variables are assigned value using the


JavaScript assignment operator, which
is the equal to (=) symbol

Assigning Values to Variables

var variablename = variablevalue;

Assigning Values to Variables

var variablename = variablevalue;


var salary = 15000;

Assigning Values to Variables


numeric
value

keywor
d

var salary = 15000;

variable

assignmen
t operator

Assigning Values to Variables


statement assigns
value of 15000 to the
variable salary

var salary = 15000;

Assigning Values to Variables


Most programming languages require variable
declaration and assignment
JavaScript allows a certain degree of flexibility in
many cases
No variable declaration at beginning of
declaration statement
No semicolon at end of declaration statement

Assigning Values to Variables


salary = 15000;
var salary = 15000
salary = 15000

Assigning Values to Variables


Good programming practice to declare
variables
Makes code easier to read and
understand
Helpful in debugging

Naming Variables
Factors to consider when naming
variables:
Case sensitivity
Invalid characters
Reserved names
Easy to remember and meaningful names

Using Case in Variables


JavaScript variables are case sensitive
salary
SALARY
SaLaRy
sAlArY

4 different variables

Using Case in Variables


Adopt a naming convention and use consistently
throughout your code
salary
SALARY
SaLaRy
sAlArY

Using Case in Variables


For variable with one word, keep it all in
lowercase
salary

Using Case in Variables


For variable with two words, use
capitalization
MySalary
mySalary
My_Salary

Using Allowed Characters


A variable name must begin with a letter
character (a-z or A-Z) or the underscore
(_) character
A variable name cannot begin with a
number or any other character that is not a
letter (other than the underscore)

Using Allowed Characters


Other characters allowed in variable name
Letters
Numbers
Underscores

Blank spaces not allowed


Special characters not allowed (e.g., #, @)

Using Allowed Characters


Valid variable names
salary
_salary
sal_ary
salary1

Using Allowed Characters


Invalid variable names
1salary
#salary
sal ary

Avoiding Reserved Words


Avoid use of JavaScript reserved words
Reserved words are special words used for a
specific purpose in JavaScript
Using reserved words can cause problems in the
JavaScript code

E.g., var, while, if

JavaScript Reserved Words


abstract

delete

function

null

throw

boolean

do

goto

package

throws

break

double

if

private

transient

byte

else

implements protected

true

case

enum

import

public

try

catch

export

in

return

typeof

char

extends

instanceof

short

var

class

false

int

static

void

const

final

interface

super

volatile

continue

finally

long

switch

while

debugger

float

native

synchronized with

default

for

new

this

Giving Variables Meaningful


Names
Variable names should clearly describe
what they represent
var x = 15000

Giving Variables Meaningful


Names
var x = 15000
var salary = 15000

Variable Types
In JavaScript, variable values, or variable
types (a.k.a. data types) can include:
Numbers
Strings
Booleans
Nulls

Variable Types
Unlike stricter programming languages (C,
C++, Java), JavaScript does not force you
to declare the type of variable when you
define it
JavaScript allows any value to be
assigned to any variable

Number Variables
Any number, e.g., 7, -2, 3.453
Do not need to declare variables as
integers, floating-point numbers

Number Variables
var variablename = number;
var salary = 15000;
var phonebill = 5000;
var savings = 0;
var sparetime = -20;

Number Variables
For long numbers, use exponential
notation
452,000

Number Variables
4.52 x 105 (452,000)

var bigNumber = 4.52e5;

String Variables
String variables represent a string of text
String can contain
Letters
Words
Spaces
Numbers
Symbols

String Variables
var variablename = stringtext;

String Variables
var myCar = Toyota
var myFutureCar = My dream car is a BMW
var myComputer = Pentium 4, 3GHz, 500MB
RAM, 80GB Hard Drive
var mySlang = @#*%$#!

Quotation Marks in String Variables


Strings must have opening and closing
quotation marks
Both double and single quotes can be
used to define a string value
String must be opened and closed with
same type of quotes

Quotation Marks in String Variables


var myHouse = small tent
myUniversity = UMT

Case Sensitivity in String Variables


JavaScript strings are case sensitive
Two different strings:
My car is fun to drive!
my car is fun to drive!

Escaping Characters in String


Variables
JavaScript allows certain characters to be
escaped
Print the following sentence on a Web
page:
Mr. Ali said, We will bury you

Escaping Characters in String


Variables
<SCRIPT language=JavaScript>
<!
document.write(Mr. Ali said, \We will bury
you.\);
//-->
<SCRIPT>

Boolean Variables
Boolean variable has value of either true
or false, or 1 (true) or 0 (false)
var variablename = booleanvalue;
var bike = true;
var car = false;

Null Variables
Means that variable has no value
It is not a space, nor is it a zero
var variablename = null;

Using Variables in Scripts


Making a call to a variable
Adding variables to text strings

Making a Call to a Variable


<SCRIPT language = JavaScript>
<!-var myCar = BMW;
document.write(myCar);
//-->
</SCRIPT>

Adding Variables to Text Strings


<SCRIPT language = JavaScript>
<!-var myCar = BMW;
document.write(myCar+
is my favourite car.);
//-->
</SCRIPT>

Adding Variables to Text Strings


<SCRIPT language = JavaScript>
<!-var myCar = BMW;
document.write(myCar+is my favourite
car.);
//-->
</SCRIPT>

Adding Variables to Text Strings


<SCRIPT language = JavaScript>
<!-var myCar = BMW;
document.write(The dacoits stole my
+myCar+ last night.);
//-->
</SCRIPT>

Adding Variables to Text Strings


<SCRIPT language = JavaScript>
<!-var myCar = BMW;
document.write(I like driving my +myCar+
every day!);
//-->
</SCRIPT>

Adding Variables to Text Strings


<SCRIPT language = JavaScript>
<!-var firstString = I like driving my ;
var myCar = BMW;
var secondString = every day!
document.write(firstString+myCar+secondString);
//-->
</SCRIPT>

now lets create a page of JavaScript

Creating the Framework


<HTML>
<HEAD>
<TITLE>A Page of JavaScript</TITLE>
</HEAD>
<BODY>
<SCRIPT language = JavaScript>
<!
Script will go here
//-->
</SCRIPT>
</BODY>
</HTML>

Defining the Variables


var headingText = <H1>A Page of JavaScript</H1>;
document.write(headingText);
var myIntro = Hello, welcome to my JavaScript page!;
var linkTag = <A HREF=http://www.umt.edu.pk>UMT</A>;
var redText = <FONT color = red>I am so colorful today!
</FONT>;
var beginEffect = <B>;
var endEffect = </B>;
var beginPara = <P>;

Adding Commands
document.write(headText);
document.write(beginEffect + myIntro + endEffect);
document.write(newSection);
document.write(linkTag);
document.write(newSection);
document.write(redText)

<HTML>
<HEAD>
<TITLE>A Page of JavaScript</TITLE>
</HEAD>
<BODY>
<SCRIPT language = JavaScript>
<!
var headingText = <H1>A Page of JavaScript</H1>;
document.write(headingText);
var myIntro = Hello, welcome to my JavaScript page!;
var linkTag = <A HREF=http://www.umt.edu.pk>UMT</A>;
var redText = <FONT color = red>I am so colorful today!</FONT>;
var beginEffect = <B>;
var endEffect = </B>;
var beginPara = <P>;
document.write(headText);
document.write(beginEffect + myIntro + endEffect);
document.write(newSection);
document.write(linkTag);
document.write(newSection);
document.write(redText)

//-->
</SCRIPT>
</BODY>
</HTML>

Modifying the Page


Italic instead of bold
Line break instead of new paragraph

<HTML>
<HEAD>
<TITLE>A Page of JavaScript</TITLE>
</HEAD>
<BODY>
<SCRIPT language = JavaScript>
<!
var headingText = <H1>A Page of JavaScript</H1>;
document.write(headingText);
var myIntro = Hello, welcome to my JavaScript page!;
var linkTag = <A HREF=http://www.umt.edu.pk>UMT</A>;
var redText = <FONT color = red>I am so colorful today!</FONT>;
var beginEffect = <I>;
var endEffect = </I>;
var beginPara = <BR>;
document.write(headText);
document.write(beginEffect + myIntro + endEffect);
document.write(newSection);
document.write(linkTag);
document.write(newSection);
document.write(redText)

//-->
</SCRIPT>
</BODY>
</HTML>

Você também pode gostar