Docsity

JavaScript Syntax, Slides of Mathematics

Toggle sidebar
bg1
JavaScript Syntax
Comments
Comments are sections of code that you do not want to run. A single line comment is preceded by //, while
multiline comments are surrounded by /* ... */:
va r x=10 0
2// T hi s is a c om me n t; i t wi ll b e ig n or ed w hen t he c od e is r un
4va r y=50 / / Th is i s a co mm en t o n the sa me l in e as s om e c od e
6/* T hi s is a l on ge r
co mme nt , th at
8sp a ns m ul tip le l in es */
Line Endings
Lines of JavaScript code are separated by a return character (so each line is actually on its own line) or by a
semicolon:
va r x=10 0
2va r y=50
va r a=20 ; va r b=40
Either is fine, though it’s good to be in the habit of ending lines with the ; symbol. This makes it easier to
“minify” your code, and put long scripts on a single line.
Case Sensitivity
JavaScript is a case-sensitive language, which means that the strings ’hello’, ’Hello’, and ’HELLO’ would not be
equal. JavaScript keywords, like function and for, must be written in lowercase.
Quotation Marks
Strings in JavaScript can be surrounded by either single or double quotation marks.
va r ne w St ri n g ="I 'm a st ri ng wi th d ou bl e q uo ta t io n ma r ks "
2va r aN e wS tr i ng ='T hi s is a st ri n g wi th s in gl e q uo tat io n m ar ks '
va r anotherNewString ='An d I 'm a s tr i ng w it h t oo ma n y q uo t at io n ma r ks '
The reason you’d want to use a mix of both can be seen in the color highlighting of the above example; the
apostrophe in the word ”I’m” was interpreted as the end of the string. Instead, we’ll surround the string in double
quotes:
va r anotherNewString =" An d I 'm a s t ri ng w i th to o ma n y q u ot a ti o n ma r ks "
Variables
A variable in JavaScript can hold one of several data types, including numbers, strings, arrays, booleans, functions,
objects, etc. JavaScript is a dynamic language, so we don’t need to specify the type of our variable, and we can
change it at any time. We assign a value to a variable using the ’=’ operator.
va r x=5
You can retrieve the type of a variable using the typeof operator:
va r sampleString ='He ll o wo r ld '
2va r x=fa lse
typeof sampleString // returns 'string'
4typeof x// returns 'boolean'
When naming variables, begin with a lowercase letter. You can use any combination of letters and numbers, and
the symbol. Do not include a space in the variable name.
Data Visualization with JavaScript ·Spring 2016 ·JavaScript Reference
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download JavaScript Syntax and more Slides Mathematics in PDF only on Docsity!

JavaScript Syntax

Comments

Comments are sections of code that you do not want to run. A single line comment is preceded by //, while

multiline comments are surrounded by /* ... */:

var x = 100 // This is a comment; it will be ignored when the code is run 2

var y = 50 // This is a comment on the same line as some code 4

/* This is a longer 6 comment , that spans multiple lines */ 8

Line Endings

Lines of JavaScript code are separated by a return character (so each line is actually on its own line) or by a

semicolon:

var x = 100 var y = 50 2 var a = 20; var b = 40

Either is fine, though it’s good to be in the habit of ending lines with the ; symbol. This makes it easier to

“minify” your code, and put long scripts on a single line.

Case Sensitivity

JavaScript is a case-sensitive language, which means that the strings ’hello’, ’Hello’, and ’HELLO’ would not be

equal. JavaScript keywords, like function and for, must be written in lowercase.

Quotation Marks

Strings in JavaScript can be surrounded by either single or double quotation marks.

var newString = " I 'm a string with double quotation marks " var aNewString = ' This is a string with single quotation marks ' 2 var anotherNewString = ' And I 'm a string with too many quotation marks '

The reason you’d want to use a mix of both can be seen in the color highlighting of the above example; the

apostrophe in the word ”I’m” was interpreted as the end of the string. Instead, we’ll surround the string in double

quotes:

var anotherNewString = " And I 'm a string with too many quotation marks "

Variables

A variable in JavaScript can hold one of several data types, including numbers, strings, arrays, booleans, functions,

objects, etc. JavaScript is a dynamic language, so we don’t need to specify the type of our variable, and we can

change it at any time. We assign a value to a variable using the ’=’ operator.

var x = 5

You can retrieve the type of a variable using the typeof operator:

var sampleString = ' Hello world ' var x = false 2 typeof sampleString // returns ' string ' typeof x // returns ' boolean ' 4

When naming variables, begin with a lowercase letter. You can use any combination of letters and numbers, and

the symbol. Do not include a space in the variable name.

JavaScript Control Flow

If and If-Else Statements

If statements are used to execute a block of code, given particular conditions are true.

var x = 100 var y = 50 2 if ( x > 0 ) { alert ( 'x is positive ') 4 } if ( y<2 ) { 6 alert ( 'y is small ') } 8 // there will be an alert 'x is positive ', but the second alert will not be displayed , since y < 2 is false

If-else statements are used when you want one block of code to run when a statement is true, and another to run

if the statement is false:

var x = 4 if ( x<0 ) { 2 alert ( 'x is negative ') } 4 else { alert ( 'x is not negative ') 6 } // the alert will display 'x is not negative ', since x < 0 is false 8

For even more options, use else if to test for addition conditions:

var x = 4 if ( x<0 ) { 2 alert ( 'x is negative ') } 4 else if ( x==0 ) { alert ( 'x is zero ') 6 } else { 8 alert ( 'x is positive ') } 10 // the alert will display 'x is positive ', since x<0 and x==0 are both false

For Loops

To have a block of code run a particular number of times, use a for loop. A typical for loop takes three arguments:

the beginning value, the condition that must be true for the loop to continue, and the increment.

for ( var i = 0; i < 5; i ++) { // define a variable i to be 0 , and increase i by 1 with each loop 2 // the loop will run until i is 5 ( but not including i=5 ) console.log ( i ) 4 } // the console will show 0 ,1 ,2 ,3 ,4 6

for ( var i = 4; i < 20; i=i +2) { 8 // define a variable i to be 4 , and increase i by 2 with each loop // the loop will run until i is 20 ( but not including i=5 ) 10 if ( i %2 ==0 ) { // check if i is divisible by 2 console.log ( i ) // only print i if i %2 ==0 12 } } 14 // the console will show 4 ,6 ,8 ,10 ,12 ,14 ,16 ,

Break

The break command is used to stop a loop. For instance, the following code creates an array. Then we create a

for loop that tests if the given value of x is in the array. If it is, we’ll set a boolean value equal to true:

var testArray = [1 ,10 ,2 ,8 ,3 ,15 ,11 ,7] var x = 2 2 var xHasBeenFound = false for ( var i in testArray ) { 4 if ( i==x ) { xHasBeenFound = true 6 } } 8 // xHasBeenFound is now true

Since x is actually found at index 2, there was no need to continue the search. Adding a break command will

stop the loop when it’s no longer necessary to run.

var testArray = [1 ,10 ,2 ,8 ,3 ,15 ,11 ,7] var x = 2 2 var xHasBeenFound = false for ( var i in testArray ) { 4 if ( i==x ) { xHasBeenFound = true 6 break } 8 } // xHasBeenFound is now true , and the loop stopped after only 3 runs instead of 8 10

Switch

Switch statements can be more convenient that a series of if-then-else statements. Blocks of code are executed

depending on the value of an expression.

var breed = prompt ( " What kind of dog do you have? " ) // a pop-up will display on screen asking the question 2 // the value of breed will be a string equal to whatever the user types as their answer 4 switch ( breed ) { case " English Bulldog " : // if the user typed English Bulldog: 6 alert ( " Bulldogs are courageous but gentle and were bred to bait bulls. " ) break; // end the switch statement , since we found the case 8 case " Clumber Spaniel " : alert ( " Clumber spaniels are calm but affectionate and originated in France. " ) 10 break; case " Labrador Retriever " : 12 alert ( " Labs are athletic and are excellent swimmers. " ) break; 14 case " Papillon " : alert ( " Papillons are small but intelligent dogs with long hair and big ears. " ) 16 break; default: // the user entered an expression that wasn 't on our list 18 alert ( " Sorry , I don 't know about your dog! " ) } 20

JavaScript Strings

Strings in JavaScript can be any combination of letters, numbers, and symbols, surrounded by single or double

quotes.

var sampleString = " I am a string "

All strings have a length property that returns the number of characters (including whitespace) in the string:

var sampleString = " I am a string " sampleString.length // returns 13 2

Concatenation

Two strings can be concatenated (combined into a single string) using the + symbol:

var sampleString = " I am a string " var longerString = sampleString + " and now I am longer " 2 // longerString has value " I am a string and now I am longer "

You can concatenate two strings or a string and a variable or number. Anything surrounded by quotes will be

interpreted literally.

var x = 4 var y = 2 2 var firstTry = " The sum of x and y is x + y " // firstTry value is " The sum of x and y is x + y " 4 var secondTry = " The sum of " + x + " and " + y + " is x + y " // secondTry value is " The sum of 4 and 2 is x + y " 6 var thirdTry = " The sum of " + x + " and " + y + " is " +( x + y ) // secondTry value is " The sum of 4 and 2 is 6" 8

Useful string methods

Each character in a string is given an index, starting at 0. To find the character at a particular index, use the

charAt method:

var sampleString = " I am a string " sampleString.charAt (0) // returns " I " 2 sampleString.charAt (7) // returns " s "

To find the index of a particular character or string, use the indexOf method. This will only return the first index

where the character or string appears. The method returns -1 if the string is not found.

var sampleString = " I am a string " sampleString.indexOf ( 'a ') // returns 2 2 sampleString.charAt ( ' str ') // returns 7 sampleString.charAt ( 'd ') // returns -1 4

To create a substring, use the substr method, which takes two parameters: the starting index and the length of

the substring:

var sampleString = " I am a string " var subString = sampleString.substr (4 , 8) 2 // subString has value " a string "

To split a string into array elements using a particular separator, use the split method:

var students = " Anne , Claire , Derek , John , Natalie " var studentArray = students.split ( " ," ) // split with separator , 2 // studentArray is now [" Anne " ," Claire " ," Derek " ," John " ," Natalie "]

Other useful array methods

To create a subset of a particular array, use the slice method. The method takes two parameters: the index

where the subarray should begin, and the index just after you’d like to end:

var week = [ " Sunday " ," Monday " ," Tuesday " ," Wednesday " ," Thursday " ," Friday " ," Saturday " ] var workWeek = sampleArray.slice (1 ,6) 2 // workWeek is [" Monday " ," Tuesday " ," Wednesday " ," Thursday " ," Friday "]

If your array contains only numerical values, you can arrange them into increasing order. Strings in an array are

sorted according to their unicode representation, which may not always be alphabetical.

var numberArray = [4 ,1 ,8 ,2 ,10] numberArray.sort () // numberArray is now [1 ,2 ,4 ,8 ,10] 2

Array values can be reversed:

var numberArray = [4 ,1 ,8 ,2 ,10] numberArray.reverse () // numberArray is now [10 ,2 ,8 ,1 ,4] 2

To combine two arrays into one, use the concat method:

var evenArray = [2 ,4 ,6 ,8] var oddArray = [1 ,3 ,4 ,7] 2 var numberArray = evenArray.concat ( oddArray ) // numberArray is now [1 ,2 ,3 ,4 ,5 ,6 ,7 ,8]

To apply a function to each value in an array (changing the values themselves), use the forEach method:

function addTwo ( e , i , a ) { // e is a value at index i in array a a [ i ] = e + 2 2 } var sampleArray = [1 ,2 ,3] 4 sampleArray.forEach ( addTwo ) // sampleArray is now [3 ,4 ,5]

To create a string from your array values with an optional separator, use the join method:

var x = [4 , " hello " ,9 , -2 ,3] var xString = x.join ( separator= " .. " ) 2 // xString is now 4.. hello..9..-2..

Loops and arrays

We can easily loop through array elements by using their indices:

var myArray = [1 ,2 ,3 ,4 ,5] for ( var i = 0; i < myArray.length; i ++) { 2 console.log ( myArray [ i ] ) } 4

JavaScript Objects

An object in JavaScript has properties, much like objects in real life have characteristics. The properties are variables

attached to the object and define its characteristics.

For instance, we can create a JavaScript object called ’dog’ with several properties. The value of each property can

be any variable type, such as a string, number, array, or boolean value.

var dog = new Object () dog.breed = " papillon " 2 dog.name = " Damien " dog.age = 9 4 dog.birthday = [ ' December ' , 12 , 2006] dog.color = " red and white " 6 dog.good = true

To access the property, use dot-notation. Undefined properties are returned as undefined, not null.

dog.breed // returns ' papillon ' dog.weight // returns undefined 2

Objects can also be created by listing the properties in curly braces, separating the properties and their value with a

colon. Properties and values are separated with a comma.

var dog = { breed: " papillon " , 2 name: " Damien " , age: 9 , 4 birthday: [ ' December ' , 12 , 2006] , color: " red and white " , 6 good: true , } 8

Finding the number of properties in an object

Unlike arrays, objects have no length property. However, we can find the number of properties given to an object

by getting the length of the array containing its properties:

var numberOfProperties = Object.keys ( dog ). length // numberOfProperties is now 6

Loops and objects

The values stored in an array are indexed by numbers: the first value has index 0, the next has index 1, and so

on. Properties of objects are not stored numerically, so instead of looping over an index (such as i) we instead

loop through the properties:

for ( var p in dog ) { console.log ( " The value of " + p + " is " + dog.p ) 2 } // the console will show 4 // The value of breed is papillon // The value of name is Damien 6 // The value of age is 9 // The value of birthday is [ ' December ', 12 , 2006] 8 // The value of color is red and white // The value of good is true 10

Equivalently, you can use brackets to get the value of a property. This is advised, as it works with objects in

standard and JSON format:

for ( var p in dog ) { console.log ( " The value of " + p + " is " + dog [ p ]) 2 }

JavaScript Object Notation (JSON)

JSON is not a new kind of object, but simply a particular syntax for storing objects that works particularly well

with JavaScript and AJAX. An object in JSON format is a JavaScript object, only all properties are string values

themselves:

var dog = { " breed " : " papillon " , 2 " name " : " Damien " , " age " : 9 , 4 " birthday " : [ ' December ' , 12 , 2006] , " color " : " red and white " , 6 " good " : true , } 8

To access the value of a property, use notation similar to finding the value at a particular index of an array. However,

instead of specifying a numerical index to look for, you just give the property name, also as a string:

dog [ " breed " ] // returns ' papillon ' dog [ " birthday " ][1] // returns 12 2

We can still loop over the properties of an object in JSON format:

for ( var k in dog ) { console.log ( dog [ k ] ) 2 } // prints papillon , Damien , 9 , [ ' December ', 12 , 2006] , red and white , true in console 4

Operators and Mathematics

Math Properties & Predefined Constants

Property Description Example

Math.E Euler’s constant, e 2.

Math.LN2 Natural (base e) logarithm of 2 2.

Math.LN10 Natural (base e) logarithm of 10 1.

Math.LOG10E Base 10 logarithm of e 0.

Math.PI Ratio of circle’s circumference to its diameter 3.

Math.SQRT1 2 Square root of 1/2 0.

Math.SQRT2 Square root of 2 1.

Math Methods

Method Description Example Example Returns

Math.abs(x) Absolute value of x Math.abs(-6.5) 6.

Math.acos(x) Angle θ (in rad) such that cos(θ) = x Math.acos(0.6) 0.

Math.asin(x) Angle θ (in rad) such that sin(θ) = x Math.asin(0.6) 0.

Math.atan(x) Angle θ (in rad) such that tan(θ) = x Math.atan(10) 1.

Math.atan2(x,y) Angle θ (in rad) such that tan(θ) = x/y Math.atan2(20,2) 1.

Math.ceil(x) Smallest integer greater than x Math.ceil(4.23) 5

Math.cos(x) cos(x) Math.cos(Math.PI) -

Math.exp(x) ex^ Math.ceil(4.23) 4

Math.floor(x) Greatest integer less than x Math.ceil(4.23) 4

Math.log(x) Natural logarithm of x Math.log(1) 0

Math.max(list) Largest value in list Math.max(4,6,1,9,2,-5,2) 9

Math.min(list) Smallest value in list Math.min(4,6,1,9,2,-5,2) -

Math.pow(x,y) xy^ Math.pow(4,2) 16

Math.random() Pseudo-random value between 0 and 1 Math.random() 0.

Math.round(x) Closest integer to x Math.round(3.14159) 3

Math.sin(x) sin(x) Math.sin(Math.PI/2) 1

Math.sqrt(x) Square root of x Math.sqrt(25) 5

Math.tan(x) tan(x) Math.tan(6) -0.

Arithmetic Operators

Operator Description Example Example Returns

+ Addition, String concatenation 3+6 9

”hello ”+”world” ”hello world”

  • Subtraction 12-8 4

/ Division 12/3 4

* Multiplication 2*5 10

% Modulus (remainder) 17%5 2

++ Increase by one var x = 5; x++ x is now 6

Random Values

The Math.random() method returns a pseudorandom value in the interval [0, 1), meaning it could be any value

between 0 and 1, or 0, but not 1. The function below returns a random integer between two integers a and b:

function randomBtwn (a , b ) { return Math.floor ( Math.random () *( b-a +1) + a ) 2 } var r = randomBtwn (2 ,80) // r is now a random integer between 2 and 80 4