Javascript
(cc) Droan Malik, July 2014
Overview
JavaScript is primarily a client-side language.
JavaScript is an interpreted language.
an interpreter in the browser reads over the JavaScript code,
interprets each line, and runs it. More modern browsers use a
technology known as Just-In-Time (JIT) compilation, which compiles
JavaScript to executable byte code just as it is about to run.
Node.js allow developers to run JavaScript server-side.
console.log("Hello world!");
The console.log functions prints the argument inside the console
followed by a new line.
Can omit console.log
alert("Hello world!");
Pops up a box with the argument.
alert(prompt("What is your name?"));
Pops up a box requesting an input.
Linking Javascript to HTML
<script src="code.js"></script>
The JavaScript Console
Chrome/Safari/Opera:
Open a new tab. Right click on the page and click Inspect Element. Click
on Console.
Firefox
Open the Tools menu. Go to Web Developer > Web Console.
Data and Variables
Numbers
Uses double type precision.
JavaScript has a single type for both integers and floating point
numbers.
Console.log(1+2); //3
1+2; //3
Console.log(7/8); //0.875
Special floating point numbers
1/0; // Infinity
-1/0; // -Infinity
0/0; // NaN
These values are used to signal that something strange has happened
during computation, such as a division by zero or an overflow.
Can be referred as
console.log(Infinity);
console.log(-Infinity);
console.log(NaN);
parseInt and parseFloat
For converting strings to numbers.
These functions interpret a string as a number.
parseInt(42,10); // 42
parseFloat(0.1); // 0.1
parseFloat(1e-3); // 0.001
If the second argument is omitted, parseInt tries to determine the base of the
string from the leading characters: if the string starts with 0x or 0X, the radix is
16 (hexadecimal).
If the string starts with 0, then the radix is 8 (octal) in older versions of JavaScript,
but 10 (decimal) in newer versions of JavaScript.
For this reason, it is recommended to always pass 10 as the second parameter.
The Math Library
Contains lots of useful methods and constants for working with
numbers.
Math.E Eulers constant Base of natural log ~2.7182818
Math.PI Ratio of circumference of a circle to its diameter
Math.ceil(1.1); // 2
Math.floor(1.1); // 1
Math.round(1.1); // 1
Math.round(1.5); // 2
Strings
Sequence of characters
Strings are immutable and cannot be modified, though new strings can be
created out of old ones.
"I am a string!
"Hello world!"[0] // H
"Hello" + "Dave // HelloDave
("The answer to Life, The Universe and " + 42); //with space
JavaScript does not have a multi-line string literal notation.
Var str=abc +def ;