arrays - javascript: variable defined vs function undefined -
i have 2 arrays:
array1 = ["one", "two"]; array2 = ["two", "four"];
if write:
var inetersection = array1.filter(function(n){ return array2.indexof(n) != -1 });
i right answer: "two".
but if write function:
function intersection (array1, array2){ array1.filter(function(n){ return array2.indexof(n) != -1 }); }
then console.log(intersection(array1, array2));
returns undefined
what wrong second syntax?
your function doesn't return anything. how fix it:
function intersection (array1, array2){ return array1.filter(function(n){ return array2.indexof(n) != -1 }); }
why?
so variables have value, let's start this:
var hello_world = "hello world!";
that doing it's setting value of hello_world
"hello world!"
. that's simple enough.
explanation!
now let's try function.
function addnumbers (number_1, number_2) { number_1 + number_2; }
now let's run function
addnumbers(1, 2)
undefined
why undefined
? let's go first example , type console
> "hello world!"
"hello world!"
what's happening when type string "hello world!"
retuns string. rule preset in javascript when make own functions, doesn't know return
reason is, lets take jquery example. can do:
var elem = $("#element");
let's @ first part. there function called $
, function doing lot of stuff. first, it's getting element id
element
. stores element in elem
. function might doing lot of stuff isn't returning
anything. returning setting value of function. here 2 examples:
var function_1 = function () { alert("hello!"); }; var function_2 = function () { return function () { alert("hello"); } }
now heck did in function two? here's what
var variable_1 = function_1(); console.log(variable_1);
undefined
variable_1
undefined still alerted. because ran function returned undefined. variable_1
isn't function; because variable_1
undefined. let's @ function_2
var variable_2 = function_2(); console.log(variable_2);
function () { alert("hello"); }
variable_2(); //alerts "hello!"
this bit confusing because function_2
returns function, sets variable_2
function returned. that's why works fine.
hope made sense. here's mdn page on return
Comments
Post a Comment