All posts by Victor

Intro to Javascript

  1. Open your text editor
  2. Type this code
  3. Save as “.html”
<!DOCTYPE html>
<html>
<body>
<script>
console.log("Hello world");
</script>
</body>
</html>

Select your file (left click). Then right click on your file. You can open it with the text editor (if you want to code). or open it with the browser (Chrome, Safari, Fire Fox) if you want to test your work.

Addition (a+b)

<script>
var a = 2;
var b = 3;
var c = a + b;
console.log(c);
</script>
//Explanation
//Make variable “a” and give it a value (“2”)
var a = 2;
//Make variable “b” and give it a value (“3”)
var b = 3;
//Add “a” + “b” and store the result in “c”
var c = a + b;
//Print the result
console.log(c);

Function (Addition)

function add(a, b)
{
var c = a + b;
return c;
}

var i = add(3, 4);
console.log(i);

var j = add(6, 7);
console.log(j);

var k = add(12, 14);
console.log(k);
//Explanation
// addition function
function add(a, b)
{
var c = a + b;
return c;
}

//call addition function and store the result in "i" (i=c)
var i = add(3, 4);
console.log(i);

//call addition function and store the result in "j" (j=c)
var j = add(6, 7);
console.log(j);

//call addition function and store the result in "k" (k=c)
var k = add(12, 14);
console.log(k);

Addition (counting animals)

var cats = 8;
var dogs = 9;
var total = cats + dogs;
console.log(total);
//Explanation
//Number of cats
var cats = 2;
//Number of dogs
var dogs = 3;
//Calculate number of cats & dogs
var total = cats + dogs;
//Print the result
console.log(total);

Objects

//apple object
var apple =
{
        weight: 5
}

console.log(apple);

//human object
var human = 
{
        name: "Jason",
        weight: 210
}

console.log(human);

Improved human object (can talk and eat)

var apple =
{
        weight: 5
}

var human = 
{
        name: "Jason",
        weight: 210, 
        talk: function () 
        {
        console.log("Hello people!"); 
        },
        eat: function (apple) 
        {
        apple.weight=apple.weight-1; 
        }
}

human.talk();

console.log(apple);

human.eat(apple);
human.eat(apple);
human.eat(apple);

console.log(apple);