Javascript : Object 1

9:07 PTG 0 Comments A+ a-

Objek membenarkan kita menyimpan properties dan beberapa nilai bagi object itu sendiri. Bagaimana kita nak membuat simple Object? Declare object perlu ada: 1) var 2) diikuti dengan nama objek 3) diikuti dengan tanda sama = 4) Setiap objek kemudian mempunyai tanda { 5) ada info didalam breket { tadi 6) berakhir dengan } Ini adalah contoh dimana info tiada didalam breket.

var bob = {};


Ini pula contoh objek terdiri daripada info yang dikenali sebagai property. Kaedah memasukkan property adalah nama property, diikuti tanda noktah bertindih( : ) dan nilai bagi property tersebut. Jika kita mempunyai banyak property, ianya perlu dipisahkan dengan tanda koma ( , ). Contoh seperti dibawah:



var Spencer = {
age: 22,
country: "United States"
};

// make your own object here called me
var me = {
age:27,
country:"Pulai Chondong"
};


Akses Properties Dalam Object Cara Pertama

Guna Object Literal Notation - Dot Notation

Object literal notation adalah mencipta objek baru dan meletakkan propeties didalam braket {}. Object literal notation mempunyai dua iaitu Dot Notation ( . ) dan Bracket Notation {} .

1) Dot Notation

Cara mudah adalah Var = .



var bob = {
name: "Bob Smith",
age: 30
};
var susan = {
name: "Susan Jordan",
age: 25
};
// here we save Bob's information
var name1 = bob.name;
var age1 = bob.age;
// finish this code by saving Susan's information
var name2 =susan.name;
var age2 = susan.age;


Akses Properties Dalam Object Cara Kedua

Guna Object literal notation - Bracket Notation


Object literal notation adalah mencipta objek baru dan meletakkan propeties didalam curly bracket {}. Object literal notation mempunyai dua iaitu Dot Notation ( . ) dan Bracket Notation [] .

1) Bracket Notation

// Take a look at our next example object, a dog
var dog = {
species: "greyhound",
weight: 60,
age: 4
};

var species = dog["species"];
// fill in the code to save the weight and age using bracket notation
var weight = dog["weight"];
var age =dog["age"];


Akses Properties Dalam Object Cara Ketiga
Constructor

Apa itu constructor? Constructor adalah cara mencipta objek tanpa curly bracket {}. Cipta objek menggunakan constructor iaitu mencipta objek kosong terlebih dahulu () dan syntaxnya adalah :


var objectName = new Object();


Kita sudah istihar objek tanpa properties.



var bob = new Object();



Bagaimana pula ingin masukkan properties? dengan cara kita create nama property tersebut contoh nama @ umur selepas . dan kemudian assign kepada nilai yang dikehendaki. Lihat contoh:


var bob = new Object();
bob.nama = "Bob Amirul";
bob.umur = 30;

Javascript: For (var property in dog)

5:14 PG 0 Comments A+ a-


var dog = {
species: "bulldog",
age: 3,
color: brown
};

for(var property in dog) {
console.log(property);
}


The words var and in are keywords. We need them to always be there. We can replace dog with any object that we want the for-in loop to run through. And you can think of property as a placeholder variable. You can use any word you want here.

In English, what is the code doing? It says: Assign the first property of the dog object to the variable property. Run the code (here, it is to print property to console). Then assign the second property of the dog object to the variable property. Again, run the code in the curly brackets. Keep repeating this until all the properties of the dog have been assigned to property.

Javascript: Object

2:34 PG 0 Comments A+ a-

 

- - - B a s i c s - - -

Each Object has one or more properties.
Each property consists of a property-key and it's associated value.

 var object1 = {
name: "First"
}


So object1 has 1 property
a name property with property-key name and it's associated string VALUE "FIRST"

OR

var myObj = {
type: 'fancy',
disposition: 'sunny'
}


myObj has 2 properties seperated by a comma-,,
a type property with property-key type and an associated string VALUE 'fancy'
a disposition-property with property-key disposition and
..an associated string VALUE 'sunny'.

= = = = = = = = = = = = = = = = = = = = = = =
To create an Object,
you can use the literal notation,
you directly create an Instance of the object, with the
properties being separated by a comma-,


var myObj = {
type: 'fancy',
disposition: 'sunny'
};


OR
You create an Object by the construct notation.
First you create an empty Object by way of either
myObj = new Object(); or myObj = {};
and then you attach its properties using the syntax
object-name.property-key = it's-associated-value ;
( this.name = x ; )

thus:

var myObj = {};
myObj.type = 'fancy';
myObj.disposition = 'sunny';



OR

There is also the facility Class construct notation.
The name should then start with a Capital-letter



var Person = function( theName, theAge ) {
this.name = theName;
this.age = theAge;
this.displayInstance = function() {
console.log("The displayInstance -output-"+
"\n============================" +
"\n\t name: " + this.name +
"\n\t age: " + this.age);
};
};
//now create an Instance of this Class-object
var myObj = new Person("Classy_Rocker",20);
//call the Method displayInstance which takes NO parameters
myObj.displayInstance();
console.log( myObj );


As you can see i created a function within this constructor,
they now call this function a Method.
So if in near future the course is asking you to create a method you now know
that you have to create
a property-key with an associated value being a function within an Object.

The Eight Levels of Programmers | 8 Tahap Skill Programmer

1:29 PG 0 Comments A+ a-

You want to rock, naturally! Or at least be a rockstar programmer. It's not a question that typically gets a serious answer – sort of like that other old groan-inducing interview chestnut, "what's your greatest weakness?" It's that you sometimes rock too hard, right? Innocent bystanders could get hurt.

But I think this is a different and more serious class of question, one that deserves real consideration. Not for the interviewer's benefit, but for your own benefit.

The "where do you see yourself in five years" question is sort of glib, and most people have a pat answer they give to interviewers. But it does raise some deeper concerns: what is the potential career path for a software developer? Sure, we do this stuff because we love it, and we're very fortunate in that regard. But will you be sitting in front of your computer programming when you're 50? When you're 60? What is the best possible career outcome for a programmer who aspires to be.. well, a programmer?

What if I told you, with tongue firmly planted in cheek, that there were Eight Levels of Programmers?

  1. Dead Programmer

    This is the highest level. Your code has survived and transcended your death. You are a part of the permanent historical record of computing. Other programmers study your work and writing. You may have won a Turing Award, or written influential papers, or invented one or more pieces of fundamental technology that have affected the course of programming as we know it. You don't just have a wikipedia entry – there are entire websites dedicated to studying your life and work.

    Very few programmers ever achieve this level in their own lifetimes.

    Examples: Dijkstra, Knuth, Kay

  2. Successful Programmer

    Programmers who are both well known and have created entire businesses – perhaps even whole industries – around their code. These programmers have given themselves the real freedom zero: the freedom to decide for themselves what they want to work on. And to share that freedom with their fellow programmers.

    This is the level to which most programmers should aspire. Getting to this level often depends more on business skills than programming.

    Examples: Gates, Carmack, DHH

  3. Famous Programmer

    This is also a good place to be, but not unless you also have a day job.

    You're famous in programming circles. But being famous doesn't necessarily mean you can turn a profit and support yourself. Famous is good, but successful is better. You probably work for a large, well known technology company, an influential small company, or you're a part of a modest startup team. Either way, other programmers have heard of you, and you're having a positive impact on the field.

  4. Working Programmer

    You have a successful career as a software developer. Your skills are always in demand and you never have to look very long or hard to find a great job. Your peers respect you. Every company you work with is improved and enriched in some way by your presence.

    But where do you go from there?

  5. Average Programmer

    At this level you are a good enough programmer to realize that you're not a great programmer. And you might never be.

    Talent often has little do do with success. You can be very successful if you have business and people skills. If you are an average programmer but manage to make a living at it then you aretalented, just not necessarily at coding.

    Don't knock the value of self-awareness. It's more rare than you realize. There's nothing wrong with lacking talent. Be bold. Figure out what you're good at, and pursue it. Aggressively.

  6. Amateur Programmer

    An amateur programmer loves to code, and it shows: they might be a promising student or intern, or perhaps they're contributing to open source projects, or building interesting "just for fun" applications or websites in their spare time. Their code and ideas show promise and enthusiasm.

    Being an amateur is a good thing; from this level one can rapidly rise to become a working programmer.

  7. Unknown Programmer

    The proverbial typical programmer. Joe Coder. Competent (usually) but unremarkable. Probably works for a large, anonymous MegaCorp. It's just a job, not their entire life. Nothing wrong with that, either.

  8. Bad Programmer

    People who somehow fell into the programmer role without an iota of skill or ability. Everything they touch turns into pain and suffering for their fellow programmers – with the possible exception of other Bad Programmers, who lack even the rudimentary skill required to tell that they're working with another Bad Programmer.

    Which is, perhaps, the hallmark of all Bad Programmers. These people have no business writing code of any kind – but they do, anyway.

These levels aren't entirely serious. Not every programmer aspires to the same things in their career. But it's illuminating to consider what a programmer could accomplish in ten years, twenty years, or thirty years – perhaps even a lifetime. Which notable programmers do you admire the most? What did they accomplish to earn your admiration?

In short, what do you wanna do with your life?

Source: http://www.devbattles.com/en/sand/post-765-The+Eight+Levels+of+Programmers

Javascript: Loop Mastery Practice

7:28 PTG 0 Comments A+ a-

 

LatihanKetiga2Loop

LATIHAN

Laksanakan ketiga-tiga For, Do/While dan While dalam satu aturcara.

// Write your code below!

var testFor= function(){
for (i=1;i<10;i++){
console.log ("ini adalah loop bagi for" +i);
};
};


var testDoWhile= function(){
hidupkanLoopDo=true;
do {
console.log ("Ini adalah loop bagi do untuk kali ini sahaja");
}while (hidupkanLoopDo=false);

};

var testWhile=function(){
i=1;
while(i<10){
console.log ("Ini adalah loop bagi While yang ke"+i);
++i;
}
}

testFor();
testDoWhile();
testWhile();







ini adalah loop bagi for1
ini adalah loop bagi for2
ini adalah loop bagi for3
ini adalah loop bagi for4
ini adalah loop bagi for5
ini adalah loop bagi for6
ini adalah loop bagi for7
ini adalah loop bagi for8
ini adalah loop bagi for9
Ini adalah loop bagi do untuk kali ini sahaja
Ini adalah loop bagi While yang ke1
Ini adalah loop bagi While yang ke2
Ini adalah loop bagi While yang ke3
Ini adalah loop bagi While yang ke4
Ini adalah loop bagi While yang ke5
Ini adalah loop bagi While yang ke6
Ini adalah loop bagi While yang ke7
Ini adalah loop bagi While yang ke8
Ini adalah loop bagi While yang ke9

Javascript : Do / While

7:12 PTG 0 Comments A+ a-

 

Kadang-kadang, kita ingin loop kita berjalan at least satu kali. Oleh itu kita akan menggunakan Do/While untuk jalan mudah.

var loopCondition = false;

do {
console.log("I'm gonna stop looping 'cause my condition is " + loopCondition + "!");
} while (loopCondition);


It runs once because do tells it to, but then never again because loopCondition is false!



LATIHAN



1) Guna Do/While.

2) Minta input dari user


3) Display di console.log


4) Matikan dengan falsekan kenyataan.



var getToDaChoppa = function(){
// Write your do/while loop here!
do {
var x = prompt ("Apa pilihan anda?");
console.log (x);
} while (jalankan=false);

};

getToDaChoppa();

Javascript : While Part 1

7:41 PG 0 Comments A+ a-

 

Jika for digunakan ketika kita tahu bila ia berhenti, While pula digunakan ketika kita tidak tahu bilakah dia akan berhenti.

 

understand = true;

while(understand === true){
console.log("I'm learning while loops!");
//Change the value of 'understand' here!
understand=false;

}


Namun pastikan didalam while tersebut, ada jalan untuk dia berhenti dan keluar dari while tersebut dan tidaklah ianya berpusing sahaja forever dan akhirnya membawa kepada crash sesuatu sistem akibat while yang tidak keluar2 atau infinity.


contoh diatas adalah understand=false;  adalah satu cara untuk kita hentikan penyataan while.


Brevity is the soul of programming


Ketahuilah brevity adalah key penting dlm programming, oleh itu, code diatas kita boleh ringkaskan menjadi:

understand = true;

while(understand){
console.log("I'm learning while loops!");
//Change the value of 'understand' here!
understand=false;

}

understand itu kita tidak perlu tanya ===true didalam while.


Penyataan diringkaskan seperti dibawah:

var bool = true;
while(bool){
//Do something
}


daripada:

var bool = true;
while(bool === true){
//Do something
}

 


Kedua-dua adalah sama sahaja, melainkan brevity dan kecepatan meringkas sahaja. Elakkan written the less succinct version dalam programming kita, sebaliknya teruskan  Correct it to the more elegant version!

var bool = true;

while(bool){
console.log("Less in coding is too cool!");
bool = false;
}
LATIHAN
Bina satu coding menggunakan while, dengan penyataaan I'm looping! sebanyak tiga kali menggunakan while.
Bagaimana menggunakan counter untuk while? Set variable kepada 0 di luar While, dan set counter tersebut bertambah semasa looping, dan set penyataan berhenti di While dengan nyatakan bilangan ke berapa ianya patut berhenti atau berapa kali ianya TRUE.
//Remember to set your condition outside the loop!


var loop = function(){
while(count <3){
//Your code goes here!
console.log("I'm looping!");
count++;
}
};

var count=0;
loop();





I'm looping!
I'm looping!
I'm looping!

 


CONTOH

//Remember to make your condition true outside the loop!

var soloLoop = function(){
//Your code goes here!

loopSekali=true;

while (loopSekali){
console.log("Looped once!");
loopSekali = false;
}

};

soloLoop();





Looped once!

Javascript : Loop Part 2 & Push()

6:19 PG 0 Comments A+ a-


Perbezaan Array antara dua patah perkataan @ lebih dengan satu patah perkataan. Tengok cara dia ambik aksara bagi [0].

Untuk dua perkataan atau lebih, Array akan tarik perkataan.

var myArray = ['hello', 'world'];
myArray[0]; // equals 'hello'


 



Manakala untuk satu patah perkataan, Array akan tarik aksara



var myName = 'Eric';
myName[0]; // equals 'E'


JavaScript Array push() Method



Digunakan untuk menambah new item kedalam array. Ianya berada di hujung sekali data array.



var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");






Banana,Orange,Apple,Mango,Kiwi

Javascript : Loop Part 2- Array

1:17 PG 0 Comments A+ a-

 

Variable boleh simpan number dan string, namun kita hanya boleh store 1 number atau satu string sahaja.
Mujurlah kita punyai array. Apa guna array?

a. store lists of data
b. can store different data types at the same time
c. are ordered so the position of each piece of data is fixed

var arrayName = [data, data, data];

var names = ["Mao","Gandhi","Mandela"];

var sizes = [4, 6, 3, 2, 1, 9];

var mixed = [34, "candy", "blue", 11];


 



Bila mana anda lihat  data dilingkungi dgn tanda [ ], it is an array.



Contoh:



var profile = ["Nik","IT Manager",32,4];
console.log(profile);






["Nik","IT Manager",32,4];



  1. First element in the array: profile[0]


  2. Third element in the array: profile[2]



atau jika ingin mendapatkan data 32, maka gunakan profile[2]



console.log(profile[2]);



Kalau ada 4 elemen dalam array, ok la. Bagaimana dengan 100 elemen dalam Array? Kita akan gunakan Array.



// Let's print out every element of an array using a for loop

var cities = [ "Pulai Chondong", "Melbourne", "Amman", "Helsinki", "NYC", "Kota Bharu"];

for (var i = 0; i < cities.length; i++) {
console.log("I would like to visit " + cities[i]);
}








I would like to visit Melbourne
I would like to visit Amman
I would like to visit Helsinki
I would like to visit NYC



Keyword, ianya berhenti sebelum cities.length

Javascript: Loop part 1

11:39 PTG 0 Comments A+ a-

 

Gunakan loop untuk mempermudahkan urusan kita.

// Write five console.log statements.

console.log(1);
console.log(2;
console.log(3);
console.log(4);
console.log(5);

Kepada:


for (var counter = 1; counter < 6; counter++) {
console.log(counter);
}

atau


for (var i = 1; i < 6; i = i + 1){
console.log(i);
}


 



contoh bermula dari 4 hingga ke 23:



for (var i = 4; i < 24; i = i + 1) {
console.log(i);
}


 



We can increment up by any value by writing i += x, where x is how much we want to increment up by.e.g., i += 3 counts up by 3s.





We can decrement down by any value by writing i -= x.



Contoh:




-Make it start counting from 5. Please!


-Stop the counting when it prints out 50.


-Only count every fifth number. So we want to increment i by 5.



for (var i = 5; i < 51; i+=5) {
console.log(i);
}


Contoh loop menurun adalah: 10 hingga ke 0.


for (var i = 10; i >= 0; i--) {
console.log(i);
}


 


Once more, for practice: write a forloop that gets the computer to count down from 100 until 0 by 5. This time, make sure not to print 0.

// Write your very own for loop!

for (var i=100;i>0;i-=5)
{
console.log(i);
}

Java Script: Bina Permainan Rock, Paper, Scissors

10:25 PTG 1 Comments A+ a-

 

Latihan membina game mudah.


- Declare a variable called userChoice.
- Make the variable equal to the answer we get by asking the user "Do you choose rock, paper or scissors?"

var userChoice = prompt("Do you choose rock, paper or scissors?");


 



- Under your previous code, declare a variable called computerChoice and make it equal to Math.random().



- Print out computerChoice so you can see how Math.random() works. This step isn't needed for the game - just useful for learning!



var userChoice = prompt("Do you choose rock, paper or scissors?");
computerChoice=Math.random();
console.log (computerChoice);


We have computerChoice but it now equals a random number between 0 and 1. We need to somehow translate this random number into a random choice of rock, paper, or scissors. How do we do this?!



-If computerChoice is between 0 and 0.33, make computerChoice equal to "rock".



-If computerChoice is between 0.34 and 0.66, make computerChoice equal to "paper".



-If computerChoice is between 0.67 and 1, make computerChoice equal to "scissors".



 



var userChoice = prompt("Do you choose rock, paper or scissors?");
computerChoice=Math.random();
console.log (computerChoice);
if ((computerChoice >= 0) && (computerChoice <=0.33))
{
console.log (computerChoice);
console.log ("rock");
}
else if ((computerChoice >= 0.34) && (computerChoice <=0.66))
{
console.log (computerChoice);
console.log ("paper");
}
else
{
console.log (computerChoice);
console.log ("scissors");
}


 



-We carried over the code from the previous section, but it is a comment. Leave it there for now.



-Below the comment, declare a function called compare.

It takes two parameters, choice1 and choice2.



-Inside the function, write an if statement. If choice1 === choice2, then return "The result is a tie!"



var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
} console.log("Computer: " + computerChoice);

var compare = function(choice1,choice2){
if (choice1===choice2) {
return "The result is a tie!";
}
};

compare(computerChoice,userChoice);


 








Computer: rock
"The result is a tie!"



 



 



What if choice1 is "rock"? Given choice1 is "rock",



a. if choice2 === "scissors", then "rock" wins.

b. if choice2 === "paper", then "paper" wins.





How do we structure this? It's a bit different from what we have already seen. We will first have an if statement. And then the code inside that if statement will be... another if statement!



 



var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
} console.log("Computer: " + computerChoice);

var compare = function(choice1,choice2){
if (choice1===choice2) {
return "The result is a tie!";
}
else if (choice1=="rock")
{
if (choice2 ==="scissors")
return "rock wins";
else
{
return "paper wins"
}
}
};

compare(computerChoice,userChoice);


 



SIAP!

Javascript 5 : Function Part 3 ( Dengan 2 Parameter)

1:10 PG 0 Comments A+ a-

 

Function juga dapat dijalankan dengan lebih dari 1 parameter. Lihat contoh dibawah

// Write your function starting on line 3
var areaBox= function(length,width) {
return length * width
};

areaBox(6,2);

Function untuk perimeter of a rectangle memerlukan dua parameter dan formulanya adalah : length + length + width + width. Contoh untuk function pengiraan rectangle parameter adalah seperti:

var perimeterBox= function(length,width) {
return length + length + width + width
};

perimeterBox(6,2);
 
SCOPE

Scope mungkin global atau local. Variable yang di definasikan di luar function, boleh diakses dimana-mana once diorang di declare. Mereka dipanggil  global variables and their scope is global.

For example

var globalVar = "hello";

var foo = function() {
console.log(globalVar); // prints "hello"
}




hello

Variable globalVar boleh diakses di mana-mana termasuk didalam function foo.


Manakala variable yang dideclare didalam function dikenali sebagai local variables. Mereka tidak boleh diakses di luar dari function tersebut.


For example

var bar = function() {
var localVar = "howdy";
}

console.log(localVar); // error




// error

Error terjadi kerana kita cuba print localVar di luar function.


Dibawah adalah perbezaan yang jelas penggunaan scope global dan local.

var my_number = 7; //this has global scope

var timesTwo = function(number) {
my_number = number * 2;
console.log("Inside the function my_number is: ");
console.log(my_number);
};

timesTwo(7);

console.log("Outside the function my_number is: ")
console.log(my_number);


 





Inside the function my_number is: 
14
Outside the function my_number is:
14
CONTOH LOCAL (tambar perkataan var didalam function)
var my_number = 7; //this has global scope

var timesTwo = function(number) {
var my_number = number * 2;
console.log("Inside the function my_number is: ");
console.log(my_number);
};

timesTwo(7);

console.log("Outside the function my_number is: ")
console.log(my_number);




Inside the function my_number is: 
14
Outside the function my_number is:
7

Javascript 5 : Function Part 2

8:45 PTG 0 Comments A+ a-

 

Sekarang kita sudah boleh memanggil FUNCTION. Namun ianya bukan sekadar untuk print dan display sahaja. FUNCTION juga berguna untuk memproses dan return kembali nilai tersebut.

// Parameter is a number, and we do math with that parameter
var timesTwo = function(number) {
return number * 2;
};

// Call timesTwo here!
var newNumber =timesTwo(2);
console.log(newNumber);



timesTwo adalah function yang digunakan untuk memproses nilai yang dihantar dengan mendarabkan dengan 2. Function yang dipanggil yang disertakan dgn nilai yang dihantar, akan diproses didalam timesTwo dan dihantar kembali kepada pemanggil untuk tindakan seterusnya.



Contoh:



var quarter= function (number){
return number/4;
};



if (quarter(48) % 3 === 0 ) {
console.log("The statement is true");
} else {
console.log("The statement is false");
}







The statement is true

Javascript 5 : Function (Part 1–Intro)

6:30 PTG 0 Comments A+ a-

 

Memahami konsep IF/ELSE statement perlu dalam sesuatu penggunaan pengaturcaraan. Contoh IF/ELSE adalah seperti:

var speed = 65;

// Complete the condition in the ()s on line 4
if (speed > 80 )
{
// Use console.log() to print "Slow down"
console.log("Slow Down");
}
else
{
// Use console.log() to print "Drive safe"
console.log("Drive Safe");
}


Apa itu function? Fahami konsep function sebelum membuat programming. Function boleh diumpamakan  seperti membuat cake. Dengan andaian jalan dan cara membuat cake adalah sama, cuma mungkin input kemanisan atau bahan sahaja berbeza.



Function:



1) Panaskan api sehingga 300 darjah



2) Campur semua bahan ramuan kedalam mangkuk



3) Letakkan ramuan yang telah dicampur itu kedalam oven sehingga 30 minit.




Caranya sama, cuma output sahaja yang berbeza kerana input (jumlah ramuan, kandungan gula) mungkin berbeza.  Contoh 10 sudu gula+ramuan buat kek coklet(input), kemudian kita panggil function iaitu tiga step diatas. Input diproses dan mengeluarkan output berbeza bergantung kepada input yang diberikan.



 




// This is what a function looks like:

var divideByThree = function (number) {
var val = number / 3;
console.log(val);
};

// On line 12, we call the function by name
// Here, it is called 'dividebythree'
// We tell the computer what the number input is (i.e. 6)
// The computer then runs the code inside the function!

divideByThree(6);


 



Kita menghantar nombor 6 untuk dimasukkan kedalam oven DivideByThree, Oven memproses dengan membahagikan 3 dengan 3, dan oven function mengeluarkan output iaitu 2. Jika kita masukkan input 9, function akan proses dgn bahagikan kepada 3 dan mengeluarkan output iaitu 3.




// Below is the greeting function!
// See line 7
// We can join strings together using the plus sign (+)
// See the hint for more details about how this works.

var greeting = function (name) {
console.log("Great to see you," + " " + name);
};

greeting("Mr Encraptor");
// On line 11, call the greeting function!







Great to see you, Mr Encraptor



 



Latihan:



1) Bina satu function, berikan nama FoodDemand



2) Kamu boleh masukkan apa sahaja nama makanan, tapi kami hanya ingin panggil dengan panggilan food sahaja untuk display apa yang kamu masukkan.



3) Akhiri dengan output seperti dibawah untuk display:

console.log("I want to eat" + " " + food);



 



// Write your foodDemand function below.
// Last hint: In your reusable block of code, end each line
// with a semicolon (;)
var foodDemand = function (food) {

console.log("I want to eat" + " " + food);

}

foodDemand("kek");







I want to eat kek



// Nicely written function:
var calculate = function (number) {
var val = number * 10;
console.log(val);
};


Contoh function sebelum dipanggil.

Cara panggil adalah tulis nama function dan letak input nombor yang dikehendaki.



contoh:



calculate(6);