Javascript Basics

See www.w3schools.com for lots more help! Data Types
Comments
Operators
Comparison Operators
Assignment Operators
Logical Operators
Range Operators
Ternary Operators
Bitwise Operators
Declaring Variables
Declaring Constants
Printing on the Console
Referencing GUI Objects
Creating Objects
Creating Functions
Math.random() method
If Else Statements
Switch Statements
For Loops
While Loops
random()
Arrays
Dictionary
Built In Functions
Trimming white space from a String
Number Conversions with a String
Strings
Math Constants
Math Functions
Create a Class
Play Music
Play Video
Draw on the Canvas
==================== ====================

Data Types

==================== ==================== Type ==== boolean number string function object Example 1: ========== var myVariable = 10; // a number type myVariable = "This is now a string type variable"; Example 2: ========== var x = 10; document.writeln ( "x = " + typeof myVariable ); // output is x = number ==================== ====================

Comments

==================== ==================== // this is a single line js comment /* this is a multiline js comment */ ==================== ====================

Operators

==================== ==================== + (for math operations and concatenating strings) - * / % += -= *= /= %= ==================== ====================

Comparison Operators

==================== ==================== >
>=
<
<=
==
!=
==================== ====================

Assignment Operators

==================== ==================== =
+=
-=
*=
/=
%=
&&=
||=
++
--

==================== ====================

Logical Operators

==================== ==================== !
&&
||

==================== ====================

Range Operators

==================== ==================== ==================== ====================

Ternary Operators

==================== ==================== ==================== ====================

Bitwise Operators

==================== ==================== ~x = 2's complement
& = bitwise and
| = bitwise or
^ = exclusive or
<< = shift left
>> = shift right

&=
|=
^=
<<=
>>=


=================== ===================

Declaring Variables

=================== =================== A variable name must start with a letter or an underscore. You can only use letters, underscores, and digits. Also, you cannot use any special characters in a name (no spaces, commas, etc.). Example 1: ========== var x; x = 10; Example 2: ========== var x = 10; Example 3: ========== (not recommended) var x = 4, str = "hello world"; =================== ===================

Declaring Constants

=================== =================== ======================= =======================

Printing on the Console

======================= ======================= Example 1: ========== <!DOCTYPE html>
<html>
<head>
<title>My First JavaScript Example</title>
</head>

<body>

<script type="text/javascript" language="JavaScript">
console.????
document.writeln( "Hello World" );
</script>

</body>
</html>



Example 2: ========== <!DOCTYPE html>
<html>
<head>
<title>My First JavaScript Example</title>
</head>

<body>

<script type="text/javascript" language="JavaScript">
document.writeln( "Hello World" );
</script>

<form>
<input type=button value="Press me" onClick="alert('Goodbye cruel world')">
</form>

</body>
</html>


Example 3: Javascript in external files ======================================= <script src="/j-scripts/myjscript.js" type="text/javascript">

Example 4: ========== console.log("Hello World"); ======================= =======================

Referencing GUI Objects

======================= ======================= ================ ================

Creating Objects

================ ================ ==================== ====================

Creating Functions

==================== ==================== function myFunction(a, b) {
return a * b;
}


var myFunction = function (a, b) {return a * b};
var z = myFunction(4, 3);



x = sumAll(1, 123, 500, 115, 44, 88);
function sumAll() {
var i, sum = 0;
for (i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}


var myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
myObject.fullName(); // Will return "John Doe"



var person = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
person.fullName(); // Will return "John Doe"




================================= =================================

Math.random() method

================================= ================================= ========================================================= Example: -------- //get a random number between 0-9 inclusive Math.floor(Math.random() * 10); ================================= ================================= Read from the console ================================= ================================= ================================= =================================

if else

================================= ================================= Example 1: ---------- var myResult = (x > y) ? x-- : x++;


Example 2:
----------

if (boolean expression)
{
// JS code to be performed when
// expression evaluates to true
}


=========================================================
var j = 5
if (j > 0)
{
some_code()
}
=========================================================



=========================================================
var disc = b*b - 4*a*c;
if (disc > 0)
{

}
else if (disc == 0)
{


}
else
{

}
=========================================================



=========================================================
if (totalSpent > discountThreshold)
{
discountPercent = 10
}
=========================================================



=========================================================
var x = 9
if x == 10
{
document.write ( "x is " + x);
}
else if (x == 9)
{
document.write ( "x is " + x);
}
else
{
document.write ( "x is " + x);
}
=========================================================

================================= =================================

Switch

================================= ================================= ================================= =================================

For Loops

================================= ================================= ================================= =================================

While Loops

================================= ================================= ================================= =================================

Math.random()

================================= ================================= Math.random() // returns a value 0-99 Math.floor(Math.random() * 100); ================================= =================================

Arrays

================================= ================================= Example 1: ---------- var list = new Array();
OR
var list = new Array ("Tom", "Bill", "Sue", "Sally");


// adding or changing elements
list[0] = "Tom";
list[1] = "Bill";
list[2] = "Sue";
list[3] = "Sally";


// to change an element
list[1] = "Tommy";


// another way to add elements (to the end)
list.push ("Tom");
list.push ("Bill");
list.push ("Sue");
list.push ("Sally");


// displaying on the web page
document.write ( list[2]);


for (var i = 0; i < list.length; i++)
{
document.write (list[i] + "<br>" );
}


for (i in list)
{
document.write (list[i] + "<br>" );
}



Example 2:
----------




Methods:
--------

list.pop(); removes and returns the last element
list.push("Jill"); adds an element to the end
list.reverse(); reverses the list
list.sort(); sorts the list small to large
list.length() returns the number of elements in the list



Forms:
------
<form action="some url" name="myForm">
<input type="TEXT" name="phoneNumber" id="phoneNumber" value="" />
</form>


var phone = document.getElementById("phoneNumber");
OR
var phone = document.myForm.elements[0];
OR
var textValue = document.myForm.elements[0].value;


document.write ( "The text is " + phone.value );
OR
document.write ( "The text is " + textValue );

// In general, an input form element is:
<input type="TEXT" name="objectname" id="object id" value="current value" size="30" click event>


Example:
<html>
<head>
<title>JavaScript Form Example</title>
<link rel="stylesheet" type="text/css" href="myStyle.css">
<script language=javascript type="text/javascript">

function buttonPressed()
{ // document.write ( document.myForm.elements[0].value );
var phone = document.getElementById("myText");
document.write ( phone.value );
}
</script>

</head>


<body>

<form action="some url" name="myForm">
<input type="TEXT" name="myText" id="myText" value="Some text" onFocus="this.select()"/>
</form>

</body>
</html>


// Other input examples:
<input type="BUTTON" name="buttonName" value="Product codes" onClick="showCodes()">

<input type="CHECKBOX" name="mailListBox" checked>Add me to the mailing List.


<form action="" name="orderForm">
<input type="CHECKBOX" name="mailListBox" checked>Add me to the mailing List.
</form>

if (document.orderForm.mailListBox.checked)
{
addToMailingList();
}

document.orderForm.mailListBox.checked = false;


// Example:

/*
<html>
<head>
<title>JavaScript Example</title>

<script language=javascript type="text/javascript">
var x=10;

function moveRight( )
{ var layerElement = document.getElementById("layer2");
x+=10;
layerElement.style.left=x;
}

function moveLeft( )
{
var layerElement = document.getElementById("layer2");
x-=10;
layerElement.style.left=x;
}
</script>
</head>

<body>

<style type="text/css">
#layer1
{
background-color: yellow;
position: absolute;
height:90px;
width:90px;
left:0px;
top:100px;
}

#layer2
{
background-color: red;
position: absolute;
height:90px;
width:90px;
left:10px;
top:100px;
}
</style>


<p id="layer1">This is layer 1</p>

<p id="layer2">This is layer 2</p>

<form action="" name="orderForm">
<input type="BUTTON" value="Move Left" onClick="moveLeft()" />
<input type="BUTTON" value="Move Right" onClick="moveRight()" />
</form>

</body>
</html>

*/


// Dictionary ================================= =================================

Dictionary (Associative Array)

Key Value Pairs ================================= ================================= ========================================================================= Example: ========================================================================= Example: ================================= ================================= =================================

Built In Functions

================================= ================================= ================================= Math.random() // 0..0.99999999999 var str = (123).toString(); ================================= ================================= =================================

Trimming white space from a String

================================= ================================= ================================= ================================= ================================= =================================

Number Conversions with a String

================================= ================================= ================================= var str = (123).toString(); var x = 123; str = x.toString(); if (x.isNumber()) // false { } ================================= ================================= =================================

Strings

================================= ================================= ================================= Methods and Properties ====================== var str = "ABC, ABC, ABC" var x = str.length x = str.indexOf("ABC") x = str.lastIndexOf("ABC") var s = str.substring(from, length) s = str.replace("ABC","DEF") s = str.toUpperCase() // returns str in all uppercase s = str.toLowerCase() // returns str in all lower case s = str.charAt(position) // returns char at position x = str.charCodeAt(position) // returns ASCII Value var array = split(", ") // returns an array ================================= ================================= ================================= Concatenating Data ================================= ================================= ================================= var first = “ro”; var second = “bot”; var together = first + " " + second; ================================= ================================= =================================

Base Arithmetic

Base 2, Base 8, Base 16, etc. ================================= ================================= ================================= var num = 15; var a = num.toString(); // base 10 var b = num.toString(2); // base 2 var c = num.toString(8); // base 8 var d = num.toString(16); // base 16 // or any base 2 to 36 ================================= ================================= =================================

Math Constants

================================= ================================= ================================= Math Constants ============== Math.E // returns Euler's number Math.PI // returns PI Math.SQRT2 // returns the square root of 2 Math.SQRT1_2 // returns the square root of 1/2 Math.LN2 // returns the natural logarithm of 2 Math.LN10 // returns the natural logarithm of 10 Math.LOG2E // returns base 2 logarithm of E Math.LOG10E // returns base 10 logarithm of E ================================= ================================= =================================

Math Functions

================================= ================================= ================================= Math functions ============== abs(x) Returns the absolute value of x acos(x) Returns the arccosine of x, in radians asin(x) Returns the arcsine of x, in radians atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians atan2(y, x) Returns the arctangent of the quotient of its arguments ceil(x) Returns the value of x rounded up to its nearest integer cos(x) Returns the cosine of x (x is in radians) exp(x) Returns the value of Ex floor(x) Returns the value of x rounded down to its nearest integer log(x) Returns the natural logarithm (base E) of x max(x, y, z, ..., n) Returns the number with the highest value min(x, y, z, ..., n) Returns the number with the lowest value pow(x, y) Returns the value of x to the power of y random() Returns a random number between 0 and 1 round(x) Returns the value of x rounded to its nearest integer sin(x) Returns the sine of x (x is in radians) sqrt(x) Returns the square root of x tan(x) Returns the tangent of an angle ================================= ================================= =================================

Creating a Class

================================= ================================= ================================= class Rectangle { constructor(height, width) { this.height = height; this.width = width; } // Getter getArea() { return this.calcArea(); } // Method calcArea() { return this.height * this.width; } } const square = new Rectangle(10, 10); console.log(square.area); // 100 ================================= ================================= =================================

Play Music

================================= ================================= ================================= // see www.w3schools.com
<!DOCTYPE html>
<html>
<body>

<audio id="myAudio">
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

<p>Click the buttons to play or pause the audio.</p>

<button onclick="playAudio()" type="button">Play Audio</button>
<button onclick="pauseAudio()" type="button">Pause Audio</button>

<script>
var x = document.getElementById("myAudio");

function playAudio() {
x.play();
}

function pauseAudio() {
x.pause();
}
</script>

</body>
</html>


<!DOCTYPE html>
<html>
<body>

<p>Click the button to create an AUDIO element with controls that will play a sound in a .mp3 or .ogg file format (depending on browser support).</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
var x = document.createElement("AUDIO");

if (x.canPlayType("audio/mpeg")) {
x.setAttribute("src","horse.mp3");
} else {
x.setAttribute("src","horse.ogg");
}

x.setAttribute("controls", "controls");
document.body.appendChild(x);
}
</script>

</body>
</html>

================================= ================================= =================================

Play Video

================================= ================================= ================================= // see www.w3schools.com <!DOCTYPE html>
<html>
<body>

<h3>A demonstration of how to access a VIDEO element</h3>

<video id="myVideo" width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

<p>Click the button to get the duration of the video, in seconds.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var x = document.getElementById("myVideo").duration;
document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>




<!DOCTYPE html>
<html>
<body>

<p>Click the button to create a VIDEO element with
controls that will play a movie.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
var x = document.createElement("VIDEO");

if (x.canPlayType("video/mp4")) {
x.setAttribute("src","movie.mp4");
} else {
x.setAttribute("src","movie.ogg");
}

x.setAttribute("width", "320");
x.setAttribute("height", "240");
x.setAttribute("controls", "controls");
document.body.appendChild(x);
}
</script>

</body>
</html>



<!DOCTYPE html>
<html>
<body>

<iframe width="420" height="345" src="https://www.youtube.com/embed/XGSy3_Czz8k">
</iframe>

</body>
</html>


================================= ================================= =================================

Draw on the Canvas

================================= ================================= ================================= // see www.w3schools.com <!DOCTYPE html>
<html>
<body>

<h3>A demonstration of how to access a CANVAS element</h3>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<p>Click the button to draw on the canvas.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(20, 20, 150, 100);
}
</script>

</body>
</html>


<!DOCTYPE html>
<html>
<head>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>

<button onclick="myFunction()">Try it</button>

<p>Click the button to create a CANVAS element, with drawings (a red rectangle).</p>

<script>
function myFunction() {
var x = document.createElement("CANVAS");
var ctx = x.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(20, 20, 150, 100);
document.body.appendChild(x);
}
</script>

</body>
</html>

================================= ================================= ================================= Ideas for programs and path ================================= ================================= ================================= Sources: Find the Area of a Rectangle Find the volume of a sphere Convert Temperatures Convert Distances Convert Measurements Show a number in base 2,8,16 Bitwise Operations fibonacci prime numbers Apps ---- The Animals app - No Code The name app - Enter your name and then display Hello Tom, welcome to Javascript! Input two numbers, which number is bigger? Random Multiplication App ? x ? Guess the number app Rock, Paper, Scissors app Letter grades if else or switch Roman Numerals print your name 10 times (for loops) calculator Tic-Tac-Toe Magic Squares Hangman Encrypt Data etc. // put it into a class Distance class Person class Student class Convert class Website for using for learning javascript www.w3schools.com https://www.w3schools.com