I'm seeing : used in code [duplicate] - javascript

This question already has answers here:
What does ':' (colon) do in JavaScript?
(11 answers)
Closed 7 years ago.
I'm seeing : used in JavaScript a good bit and I can not figure out what exactly what its doing. Is it naming something? For example is the function being named onSave? Example is below.
onSave: function() {
var properties = this.getFormData(),
request = this.wfsBody("usa", "usa:pecotest", "geom",
properties);
console.log(request);
this.makeRequest(request);enter code here

There are, as far as I know, four uses of : in JavaScript. The ternary operator, switch statements, labels, and part of JavaScript object creation.
// if a, then f is b. Otherwise it is C.
var f = a? b: c;
// This creates an object. You can now look at the object's `name` property.
var obj = {name: val}
switch(foo)
{
case 1:
// this only happens if foo === 1
break;
}
top: // this is a label
for (i = 0; items.length; i++)
for (j = 0; j < tests.length; i++)
if (!tests[j].pass(items[i])){
allPass = false;
break top; // breaks the outermost loop.
}
You'll see this also in JSON, which is JavaScript object notation:
{
"foo": 1,
"bar": [2,3],
"baz": {
"bat": 4
}
}
That is an object where
obj.foo === 1
obj.bar[0] === 2
obj.bar[1] === 3
obj.baz.bat === 4
The most common use, and certainly what most people expect when they see the above code, is that an object is being created with a property "onStart" which is a function defined as above.

: is used as an = in an object - separating the object property from its value. Objects can also have functions as values. So what you're seeing is:
var obj = {
onSave: function(){}
}
could also be obj.onSave = function(){}

Related

What exactly is the `in` keyword in JavaScript? [duplicate]

This question already has answers here:
What does the 'in' keyword in javascript mean?
(3 answers)
Closed 1 year ago.
Ok so I have seen the in keyword in many different codes but i have never understood what they do.
Here is an example
let duck = new Bird() // Bird is a constructor i made. Not important
function in keyword() {
let ownProps = [];
for (let property in duck) {
if(duck.hasOwnProperty(property)) {
ownProps.push(property);
}
}
}
Sooo, what does it do?
Please explain it to me
The in operator tests if the string on the left side of the operator is a property name in the object on the right side.
let obj = { a: 1 };
console.log("a" in obj); // true
console.log("b" in obj); // false
The in keyword also plays a role in the for ... in loop, which iterates through the properties (the enumerable properties) of an object:
let obj = { a: 1, b: 2 };
for (let x in obj) {
console.log(x);
}
That will log "a" and "b", because those are the enumerable properties of the object.

javascript mystery - how functions get access to outside variables [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 7 years ago.
I am kind of new to javascript and trying to understand some non trivial - at least so i hope :) things.
my question is general, but i have a specific example which can help me ask my question and help you understand what i mean.
the example:
function updateBookmark(bookmark){
var index = _.findIndex($scope.bookmarks, function(b){
return b.id == bookmark.id;
});
return index;
}
obviously the findIndex function is declared somewhere (in our case - lodash.js)
and it gets two parameters (at least two visible parameters: a data set, and a function)
first question:
in this example, what is b? how does b gets its value? i understand b is each of the data set's objects, but i mean - what is going behind the scenes here so b will be what it is??
second question:
the author chose to pass an anonymous function which equals b.id with bookmark.id,
i understand that he can use bookmark.id where he is using it, but how does findIndex has access to this bookmark?!
this function as i concluded earlier is declared somewhere else, does it get all the variables in the scope some how?
what is going on here?
Thanks in advance to responders and sorry for the messy question...
Jim.
If you rewrite some things, it becomes easier to understand.
Starting with the last portion:
// Q: "How does `findIndex`have access to `bookmark`"
_.findIndex(bookmarks, function (b) { });
// A: "It doesn't."
var bookmark = { id: 1 };
var bookmarks = [ /* ... */ ];
function compareWithBookmark( test ) {
return test.id === bookmark.id;
}
_.findIndex(bookmarks, compareWithBookmark);
As you can see, findIndex doesn't actually have any access to bookmark.
Rather, it has access to a function which it can pass a value to test, and that function will return whether that test passed or failed.
Under the covers of .findIndex or [].map or [].filter, they're all just taking a function, making a loop, passing each element into the function one at a time, and doing something with the return value.
function findIndex (array, test) {
var index = -1;
var i = 0;
var l = array.length;
var el;
var result;
for (; i < l; i += 1) {
el = array[i]; // <-- how `b` got its value
result = test(el, i, array); // <-- test(b)
if (!!result) {
index = i;
break;
}
}
return index;
}
The different functions would do different things with the results (map returns a new array which contains each result, filter returns an array where only !!result tests passed, et cetera), but all of them do this inner-looping.
This is also a pretty gross simplification of the looping structure and considerations, but it's exactly what's driving your expected behaviour.
Edit
Here is a full usage of the function I just defined, plus the array, plus the object I'm checking.
var bookmarks = [
{ id: 2 },
{ id: 3 },
{ id: 6 },
{ id: 14 }
];
var bookmark = { id: 3 };
function compareBookmarkIdTest (el) {
return el.id === bookmark.id;
}
var index = findIndex(bookmarks, compareBookmarkIdTest);
index; // 1
Hope that helps.

How to do a deep search of object from a given string [duplicate]

This question already has answers here:
Convert string in dot notation to get the object reference [duplicate]
(6 answers)
Closed 8 years ago.
I would like to split the str (dot seperated) and look inside an object tree, if the values exist.
To keep it simple, I have just create a simple object, but I would like it to be a deep search.
I just need the logic not necessary a working code, just a direction on what I need to do inside the exists to, check recursebly if person.name.first does exist with a boolean value true || false to be returned as the final answer.
var str = "person.name.first";
var arr = {
person: {
name: {'first':true ,'last' : true },
age : true
}
}
function exists(){
...
}
exists(str,arr);//true === exists, false === does not exist
Just try with:
function exists(str, arr) {
var parts = str.split('.');
for (var i = 0; i < parts.length; i++ ) {
if (arr.hasOwnProperty(parts[i])) {
arr = arr[parts[i]];
} else {
return false;
}
}
return true;
}

Get JSON property from fully qualified string [duplicate]

This question already has answers here:
Convert string in dot notation to get the object reference [duplicate]
(6 answers)
is it evil to use eval to convert a string to a function? [closed]
(4 answers)
Closed 10 years ago.
Say I have a JSON object like this:
var a = {
"b" : {
"c" : 1
}
}
is there a quick way to get at c when I know the string "b.c" ?
I guess I could split the string by dots then drill down into c from that but I was hoping there was a quick way to do this in one go.
like I was hoping maybe var c = a["b.c"] but that doesnt work
How about something like this, as you suggested using a split:
var a = {
"b" : {
"c" : 1
}
}
var n = "b.c".split(".");
var x = a;
for(var i = 0; i < n.length; i++){
x = x[n[i]];
}
//x should now equal a.b.c
Here is a working example
In the event that the path is not valid, there is some extra checking that should be done. As my code stands above, x will be undefined if the final part of the path is invalid (e.g "b.d"). If any other part of the path is invalid (e.g. "d.c") then the javascript will error.
Here is a modified example that will end the loop at the first instance of undefined, this will leave x as undefined and will ensure the javascript can continue to execute (no error!)...
var n = "d.c".split(".");
var x = a;
for (var i = 0; i < n.length; i++) {
x = x[n[i]];
if (typeof(x) == "undefined") {
break;
}
}
Here is an example of this in action
var a = {
"b" : {
"c" : 1
}
}
var c = "b.c".split(".").reduce(function(obj, key) {
return obj[key];
}, a);
alert(c)
See reduce. The link also show a how to implement shim for the browsers that doesn't support ES5. Notice that this code is simplified, assumes the keys are present in the objects.

Defining methods in a loop from an array of method names [duplicate]

This question already has answers here:
Javascript infamous Loop issue? [duplicate]
(5 answers)
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
I want to define several methods from an array of method names like so:
var methodNames = ['foo', 'bar', 'baz'],
randomObject = {}, method;
for( var i = methodNames.length - 1; i >= 0; --i ){
method = methodNames[ i ];
randomObject[ method ] = function(){
console.log( method );
}
}
So that I end up with an object randomObject, which has all the methods defined doing the exact same thing. The problem is, every method logs 'foo' instead of the name of the method being called. How can I make the variable method persist when the method is called?
I can't tell if this is the best way to use a closure, but I think this is working...
UPDATE:
http://jsfiddle.net/ZDrCK/1/
var methodNames = ['foo', 'bar', 'baz'],
randomObject = {},
method;
for (var i = methodNames.length - 1; i >= 0; --i) {
method = methodNames[i];
randomObject[method] = (function(met){
return function () {
console.log(met);
}
})(method);
}
randomObject.baz();
randomObject.bar();
randomObject.foo();
You should wrap it in a self-executing closure:
for (var i = methodNames.length - 1; i >= 0; --i) {
(function(method) {
randomObject[method] = function() {
console.log(method);
};
})(methodNames[i]);
}​

Categories