Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: why no keys in the javascript objects

Looking into redux todomvc, why no keys between the following {}? e.g. no keys before text and id in the following? A little confused.

import * as types from '../constants/ActionTypes'

export const addTodo = text => ({ type: types.ADD_TODO, text })
export const deleteTodo = id => ({ type: types.DELETE_TODO, id })
export const editTodo = (id, text) => ({ type: types.EDIT_TODO, id, text })
export const completeTodo = id => ({ type: types.COMPLETE_TODO, id })
export const completeAll = () => ({ type: types.COMPLETE_ALL })
export const clearCompleted = () => ({ type: types.CLEAR_COMPLETED })

Any comments welcomed. Thanks.

UPDATE

Thank you for the answers and comments. I found my question is a little stupid. Currently, I am learning react and redux for fun. I am not familiar with es2015. sometimes, I cannot distinguish between 2015es new syntax and redux syntax. Thanks.

like image 395
BAE Avatar asked Nov 07 '16 15:11

BAE


People also ask

Does JavaScript object have key?

Objects in JavaScript are non-primitive data types that hold an unordered collection of key-value pairs. As you can see in the image above, the key is the property, and each object value must have a key. When interacting with objects, situations might arise that require you to check if a particular key exists.

How do you check if key does not exists in object JavaScript?

Example 2: Check if Key Exists in Object Using hasOwnProperty() The key exists. In the above program, the hasOwnProperty() method is used to check if a key exists in an object. The hasOwnProperty() method returns true if the specified key is in the object, otherwise it returns false .

How do you know if an object has no key?

Using the Object. If no keys are present, the object is empty: Object. keys(obj). length === 0 && obj.


1 Answers

In an ES2015 (and JSX) object initializer, you can create a property on an object by giving just the name of a variable without a value after it; the property's name will be the same as the variable's name, and the property's value will be the value of the variable:

let one = 1;
let obj = {one};
console.log(obj.one); // 1

So on this line:

export const addTodo = text => ({ type: types.ADD_TODO, text })

it's not that the key (property name) isn't there, it's that the value isn't there (explicitly) for the text property. It's exactly as though it were written like this:

export const addTodo = text => ({ type: types.ADD_TODO, text: text })
// ---------------------------------------------------------^^^^^^

It's just shorthand. But it's amazing how often it's useful.

like image 153
T.J. Crowder Avatar answered Oct 22 '22 09:10

T.J. Crowder